简体   繁体   中英

c++ thread alive?

How to?

I tried a WaitingForSingleObject, GetExitCodeThread and etc., but when i kill thread with process explorer nothing happens.

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

When a thread is killed forcibly, eg from the task manager or from Process Explorer, that does not change the thread ID. The thread handle still exists because your process has not yet closed it. And the thread ID associated with that thread still exists. So GetThreadId will always return a non-zero value.

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. 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 . To the best of my knowledge you cannot discern by means of the Windows API that your thread was killed abnormally.

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. When the thread terminates normally, set the flag to 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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