Mutex示例中未处理的异常/访问冲突写入位置

Eil*_*idh 9 c++ winapi multithreading critical-section waitformultipleobjects

我正在研究一个使用互斥锁来保护全局双精度的例子,但是我得到了错误 -

Lab7.exe中0x77b6308e处的未处理异常:0xC0000005:访问冲突写入位置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, 0, MyThread, NULL, 0, NULL); 
    }

    WaitForMultipleObjects(10, threads, 0, INFINITE); 

    DeleteCriticalSection(&score_mutex); 

    std::cout << score; 

    while(true);

}
Run Code Online (Sandbox Code Playgroud)

更新:

在将循环设置为1000而不是10来解决问题之后,错误仍然存​​在,但是当我注释掉引用互斥锁的代码时,错误没有发生.

CRITICAL_SECTION score_mutex; 
EnterCriticalSection(&score_mutex); 
LeaveCriticalSection(&score_mutex); 
InitializeCriticalSection(&score_mutex); 
DeleteCriticalSection(&score_mutex); 
Run Code Online (Sandbox Code Playgroud)

更新2

线程按照惯例返回0(这是一个漫长的一周!)

我尝试在互斥量相关的代码中添加,并且程序将编译并运行正常(除了竞争条件问题与双重当然)与CRITICAL_SECTION,InitializeCriticalSection和DeleteCriticalSection都重新加入.问题似乎与EnterCriticalSection或LeaveCriticalSection,因为我添加它时错误再次出现.

And*_*ron 13

您的代码中的剩余错误是在调用中WaitForMultipleObjects().您将第3个参数设置为0(FALSE),以便主线程在10个线程中的任何一个完成后立即解除阻塞.

这会导致调用DeleteCriticalSection()在所有线程完成之前执行,在其中一个(可能)其他线程启动并调用时创建访问冲突EnterCriticalSection().