我正在使用保护全局双倍使用互斥锁的示例,但是我得到了错误 -

0x77b6308e的未处理异常 Lab7.exe: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);

}
.

更新:

将循环设置为1000而不是10的循环修复问题后,仍会发生错误,但是当我注释出代码指示互斥锁的代码时,不会发生错误。

CRITICAL_SECTION score_mutex; 
EnterCriticalSection(&score_mutex); 
LeaveCriticalSection(&score_mutex); 
InitializeCriticalSection(&score_mutex); 
DeleteCriticalSection(&score_mutex); 
.

更新2

线程根据惯例返回0(已经很长一周!)

我尝试在互斥锁相关的代码中加回来,程序将编译和运行罚款(除了双重课程的竞争条件问题之外)与Allicallant ag中加入的italy_cection,initialInutysection和deletecriticalection。问题出现了与enterCriticalsection或Leavecriticalsection一起,因为我添加它们时会重新忽略。

有帮助吗?

解决方案

The remaining bug in your code is in the call to WaitForMultipleObjects(). You set the 3rd parameter to 0 (FALSE) such that the main thread unblocks as soon as any of the 10 threads finishes.

This causes the call to DeleteCriticalSection() to execute before all threads are finished, creating an access violation when one of the (possibly) 9 other threads starts and calls EnterCriticalSection().

其他提示

You're writing beyond the end of your threads[10] array:

for (int loop = 0; loop < 1000; loop++){
     threads[loop];
}

threads only has size 10!

Your problem is that WaitForMultipleObjects is not waiting for all the threads to complete, causing the critical section to be prematurely deleted. According to MSDN, the third argument is

bWaitAll [in]

If this parameter is TRUE, the function returns when the state of all objects in the >lpHandles array is signaled. If FALSE, the function returns when the state of any one of >the objects is set to signaled. In the latter case, the return value indicates the object >whose state caused the function to return.

You set this to 0, which returns when ANY ONE of your threads completes. This causes the following DeleteCriticalSection to be run while there's still threads waiting to access it.

You should also declare score as a volatile so you don't have cached value problem.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top