How to check whether the thread is alive or dead?
In multi-threaded environments, sometimes we need to check whether a given thread is alive or not. But how can we check it?

Picture courtesy – Erica Marshall
![]()
You can use the function – GetExitCodeThread(). If thread is alive, the function returns STILL_ACTIVE. Have a look at the code snippet.
// Checks whether given thread is alive.
bool IsThreadAlive(const HANDLE hThread, bool& bAlive )
{
// Read thread's exit code.
DWORD dwExitCode = 0;
if( GetExitCodeThread(hThread, &dwExitCode))
{
// if return code is STILL_ACTIVE,
// then thread is live.
bAlive = (dwExitCode == STILL_ACTIVE);
return true;
}
// Check failed.
return false;
}
void main()
{
bool bAlive = false;
if( IsThreadAlive( GetCurrentThread(), bAlive))
{
// IsThreadAlive is success.
// Now check whether thread is alive.
// It should, because its our main thread.
if( bAlive)
{
std::cout << "Thread Alive!!!";
}
}
}
Sounds like a trick you should try to avoid, due to race condition issues. Theres a chance that IsThreadAlive will identify the thread as alive, but by the time it returned the value the thread has already exited. Having to use this check might imply a design problem.
Also, IIRC, you can WaitForSingleObject on the thread’s handle. Set the timeout limit to 0, and check the returned value. If WFSO timed out, the thread is still running. This does not solve the race condition, of course, it’s just an alternative to the offered trick.