我试图通过使用互斥锁来保护一段代码。由于代码崩溃,我在下面创建了一个简单的测试代码,它的作用相同。崩溃不一定每次都在同一行代码上,但总是围绕“WaitForSingleObject”或“Sleep”调用。
任何援助将不胜感激。
#include <thread>
#include <windows.h>
#include <process.h>
static HANDLE myMutex;
//The function we want to make the thread run.
void task1()
{
WaitForSingleObject(myMutex, INFINITE);
for (int i = 0; i < 20; i++)
{
Sleep(500);
}
ReleaseMutex(myMutex);
}
void task2()
{
Sleep(10);
WaitForSingleObject(myMutex, INFINITE);
for (int i = 0; i < 20; i++)
{
Sleep(10);
}
ReleaseMutex(myMutex);
}
int main(int argc, char **argv)
{
myMutex = CreateMutex(0, FALSE, 0);
std::thread t1(task1);
std::thread t2(task2);
}