繁体   English   中英

如何终止等待对象的辅助线程

[英]How can I terminate a secondary thread waiting for an object

我使用_beginthreadex创建了一个辅助线程。 当进程想要停止时。 它必须终止两个线程。 问题是辅助线程正在等待一些句柄(使用WaitForSingleObject )并且主线程想要终止辅助线程。

主线程如何通过WaitForSingleObject通知第二个线程停止然后终止?

添加用于停止线程的新事件:

HANDLE hStopEvent;
hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

要阻止另一个线程:

SetEvent(hStopEvent);    // ask thread to stop
WaitForSingleObject(hThread, INFINITE);   // wait when thread stops

在线程代码中,将WaitForSingleObject替换为WaitForMultipleObjects 等待exitsting事件+ hStopEvent 发出hStopEvent信号时,退出线程功能。

HANDLE hEvents[2];
hEvents[0] = <your existing event>;
hEvents[1] = hStopEvent;

for(;;)      // event handling loop
{
    DWORD dw = WaitForMultipleObjects(2, hEvents, FALSE, INFINITE);

    if ( dw == WAIT_OBJECT_0 )
    {
         // your current event handling code goes here
         // ...
    }
    else if ( dw == WAIT_OBJECT_0 + 1 )
    {
        // stop event is set, exit the loop and thread function
        break;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM