In multi-threaded environments, sometimes we need to check whether a given thread is alive or not. But how can we check it?
Image may be NSFW.
Clik here to view.
Picture courtesy – Erica Marshall
Image may be NSFW.
Clik here to view.
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. Image may be NSFW.
Clik here to view.
if( bAlive)
{
std::cout << "Thread Alive!!!";
}
}
}