c++ - 等待单个对象崩溃

标签 c++ windows waitforsingleobject

我试图通过使用互斥体来保护一段代码。由于代码崩溃,我在下面创建了一些简单的测试代码,其功能相同。崩溃不一定每次都发生在同一行代码上,但总是围绕“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/

相关文章:

mysql - 如何将数据库名称从批处理传递到mysql脚本

windows - Azure Web 角色入口点和 .aspx 页面处理程序在不同进程中运行是如何发生的?

windows - ANT 构建脚本如何终止 Windows 进程?

c++ - 为什么我的变量在 WaitForSingleObject 之后没有保持状态?

multithreading - 使用 WaitForSingleObject() 等待线程完成

c++ - 等待单个对象函数的使用

c++ - 使用 boost::python 将回调从 python 传递到 c++

c++ 模板在 vs express 2015 中看不到

c++ - Shiboken2 和自定义 Qt 小部件

c++ - 创建具有不同参数的模板函数