Visual C++ and beyond!
Archive for March, 2010
How to check whether the thread is alive or dead?
113 years ago
by Jijo Raj
in Visual C++
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!!!";
}
}
}
Recent Comments