我正在通过使用互斥体来保护全局双重的例子,但是我收到错误 –
Unhandled exception at 0x77b6308e in
Lab7.exe: 0xC0000005: Access violation
writing location 0x00000068.
我认为这与访问得分有关? (全球双倍)
#include <windows.h> #include <iostream> #include <process.h> double score = 0.0; HANDLE threads[10]; CRITICAL_SECTION score_mutex; unsigned int __stdcall MyThread(void *data) { EnterCriticalSection(&score_mutex); score = score + 1.0; LeaveCriticalSection(&score_mutex); return 0; } int main() { InitializeCriticalSection(&score_mutex); for (int loop = 0; loop < 10; loop++) { threads[loop] = (HANDLE) _beginthreadex(NULL,MyThread,NULL,NULL); } WaitForMultipleObjects(10,threads,INFINITE); DeleteCriticalSection(&score_mutex); std::cout << score; while(true); }
更新:
在将循环设置为1000而不是10的问题修复后,仍然出现错误,但是当我注释掉引用互斥量的代码时,错误没有发生.
CRITICAL_SECTION score_mutex; EnterCriticalSection(&score_mutex); LeaveCriticalSection(&score_mutex); InitializeCriticalSection(&score_mutex); DeleteCriticalSection(&score_mutex);
更新2
线程根据约定返回0(这是一个漫长的一周!)
我尝试加入互斥体相关的代码,并且程序将编译并运行正常(除了当然的两个竞争条件问题)与CRITICAL_SECTION,InitializeCriticalSection和DeleteCriticalSection全部添加回来.问题似乎是与EnterCriticalSection或LeaveCriticalSection,因为我添加它们时会重现该错误.