简体   繁体   English

C ++线程还活着吗?

[英]c++ thread alive?

How to? 如何?

I tried a WaitingForSingleObject, GetExitCodeThread and etc., but when i kill thread with process explorer nothing happens. 我尝试了WaitingForSingleObject,GetExitCodeThread等,但是当我用进程资源管理器杀死线程时,什么也没发生。

while(true)
{
    if(GetThreadId(this->hWatchThread) == 0) // Always return killed thread id!
        break;
}

Upd: When i kill thread, it stop working, but i can't get exit code or zero value from GetThreadId Upd:当我杀死线程时,它停止工作,但是我无法从GetThreadId获取退出代码或零值

When a thread is killed forcibly, eg from the task manager or from Process Explorer, that does not change the thread ID. 当从任务管理器或Process Explorer中强行杀死线程时,这不会更改线程ID。 The thread handle still exists because your process has not yet closed it. 线程句柄仍然存在,因为您的进程尚未关闭它。 And the thread ID associated with that thread still exists. 并且与该线程关联的线程ID仍然存在。 So GetThreadId will always return a non-zero value. 因此, GetThreadId将始终返回非零值。

As for the exit code, you can't get a meaningful value for the exit code because the thread did not exit. 至于退出代码,因为线程没有退出,所以您无法获得有意义的退出代码值。 It was killed. 它被杀死了。 It never had a chance to set an exit code. 它从来没有机会设置退出代码。

What you must do is use one of the wait functions, eg WaitForSingleObject , to wait on your thread handle. 您必须做的是使用其中一个等待函数,例如WaitForSingleObject ,以等待线程句柄。 If that wait terminates because the thread was killed, then the wait function will return and report a successful wait and the thread exit code will be reported as 0 . 如果该等待由于线程被杀死而终止,则wait函数将返回并报告成功的等待,并且线程退出代码将报告为0 To the best of my knowledge you cannot discern by means of the Windows API that your thread was killed abnormally. 据我所知,您无法通过Windows API来识别线程被异常杀死。

What you could do is use your own mechanism to indicate that termination was abnormal. 您可以使用自己的机制来指示终止是异常的。 Create a flag, owned by the thread, to record that termination was normal. 创建一个线程拥有的标志,以记录终止是正常的。 Set the flag to false when the thread starts executing. 当线程开始执行时,将标志设置为false。 When the thread terminates normally, set the flag to true. 当线程正常终止时,将标志设置为true。 This way you can tell whether or not the thread was terminated abnormally by reading the value of that flag after the thread terminates. 这样,您可以通过在线程终止后读取该标志的值来判断线程是否异常终止。

If you want to do something after the thread has exited: 如果要在线程退出后执行某些操作:

WaitForSingleObject(handle_to_your_thread,INFINITE);
MessageBox(NULL,"Thread has exited","Foo",MB_ICONINFORMATION);

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

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