c++ - 退出应用程序前关闭线程

标签 c++ winapi thread-safety

我想在退出主程序之前停止线程。这段代码正确吗? (简化示例)

HANDLE hThread;
BOOL live = TRUE;



DWORD WINAPI Thread ( LPVOID lpParam )
{
..
while(live);
..
}



case WM_DESTROY:
{
live=FALSE;     
WaitForSingleObject(hThread, INFINITE);
}

最佳答案

同步线程最安全的方法是使用一些内核对象。在您的情况下,您可以使用 CreateEvent 创建“终止”事件并在线程回调函数中等待它:

#include <Windows.h>
#include <iostream>
using std::cout;
using std::cerr;
using std::endl;

DWORD WINAPI Callback(LPVOID lpVoid)
{
    HANDLE hTerminateEvent = *(reinterpret_cast<HANDLE*>(lpVoid));

    bool terminate = false;

    while(!terminate)
    {
        DWORD retVal = WaitForSingleObject(hTerminateEvent, 0);

        switch(retVal)
        {
            case WAIT_OBJECT_0: 
                cout << "Terminate Event signalled" << endl;
                terminate = true;
                break;
            case WAIT_TIMEOUT:
                cout << "Keep running..." << endl;
                Sleep(1000);
                break;
            case WAIT_FAILED:
                cerr << "WaitForSingleObject() failed" << endl;
                terminate = true;
                break;
        }
    }

    return 0;
}

int main()
{
    DWORD threadID = 0;
    HANDLE hTerminateEvent = CreateEvent(0, FALSE, FALSE, 0);
    HANDLE hThread = CreateThread(0, 0, Callback, &hTerminateEvent, 0, &threadID);  

    // allow some time to thread to live
    Sleep(20000);

    // set terminate event
    if(!SetEvent(hTerminateEvent))
    {
        cerr << "SetEvent() failed" << endl;        
        return 1;
    }

    // wait for thread to terminate
    DWORD retVal = WaitForSingleObject(hThread, INFINITE);

    switch(retVal)
    {
        case WAIT_OBJECT_0: 
            cout << "Thread terminated" << endl;            
            break;
        case WAIT_FAILED:
            cerr << "WaitForSingleObject() failed" << endl;         
            break;
    }

    CloseHandle(hThread);
    CloseHandle(hTerminateEvent);

    return 0;
}

输出:

Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Keep running...
Terminate Event signalled
Thread terminated

关于c++ - 退出应用程序前关闭线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10137708/

相关文章:

c++ - 安装 Cyber​​link for C++ 时出错

c++ - 传递 const 引用 : performance increase?

c++ - 使用坐标空间和变换滚动和缩放增强型 Windows 图元文件

c++ - win32 API编程

c# - 线程安全问题

C++ 对象创建

c++ - QProgressBar : Change color while keeping OS style

c++ - 如何从 C++ 中的资源文件加载游标组?

C++线程安全——读图

c++ - 当在其他地方使用相同的互斥锁和 lock_guard 时,在 unique_lock 互斥锁上等待/通知是否安全?