Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I determine if a Win32 thread has terminated?

How can I determine if a Win32 thread has terminated?

The documentation for GetExitCodeThread warns to not to use it for this reason since the error code STILL_ACTIVE can be returned for other reasons.

Thanks for the help! :)

like image 464
Uhall Avatar asked Nov 19 '08 05:11

Uhall


People also ask

What happens when a thread is terminated?

When a thread terminates, its termination status changes from STILL_ACTIVE to the exit code of the thread. When a thread terminates, the state of the thread object changes to signaled, releasing any other threads that had been waiting for the thread to terminate.

How do I close a thread in win32?

You can terminate thread by using TerminateThread() using the thread handle you got from CreateThread. PS:It is mentioned in website: "TerminateThread is a dangerous function that should only be used in the most extreme cases.

How do you terminate a thread in C++?

The C++11 does not have direct method to terminate the threads. The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object.


2 Answers

MSDN mentions that "When a thread terminates, the thread object attains a signaled state, satisfying any threads that were waiting on the object".

So, you can check for whether a thread has terminated by checking the state of the thread handle - whether it's signaled or not:

DWORD result = WaitForSingleObject( hThread, 0);

if (result == WAIT_OBJECT_0) {
    // the thread handle is signaled - the thread has terminated
}
else {
    // the thread handle is not signaled - the thread is still alive
}
like image 133
Michael Burr Avatar answered Sep 28 '22 10:09

Michael Burr


The documentation you link to warns against using STILL_ACTIVE as a return code, since it can't be distinguished from the return value used to indicate an active thread. So don't use it as a return value and you won't have this problem.

like image 42
Shog9 Avatar answered Sep 28 '22 10:09

Shog9