我试图通过使用互斥体来保护一段代码。由于代码崩溃,我在下面创建了一些简单的测试代码,其功能相同。崩溃不一定每次都发生在同一行代码上,但总是围绕“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);
}
最佳答案
问题是您没有在 main
方法退出之前等待线程退出。 thread
对象上的析构函数在线程不退出的情况下被调用。您需要调用 join
才能让您的主要方法等待。尝试:
int main(int argc, char **argv)
{
myMutex = CreateMutex(0, FALSE, 0);
std::thread t1(task1);
std::thread t2(task2);
if(t1.joinable())
t1.join();
if(t2.joinable())
t2.join();
}
根据 std::thread destructor文档:
Destroys the thread object. If *this still has an associated running thread (i.e. joinable() == true), std::terminate() is called.
关于c++ - 等待单个对象崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20569542/