Gold mine of Visual C++ tricks!
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.
Hi eran,
I guess it should be all fine since here it is checking for thread status. The application should not return 259 (STILL_ACTIVE) which can cause confusion.
I agree that there is also another way to handle this
if(WaitForSingleObject(GetCurrentThread(), 0) == WAIT_OBJECT_0)
{
//TERMINATED;
}
I would say if you need to check this then it indicates a smell that something is not correct. If you really need to know when a thread is finished wait on a semaphore/condition variable.
can you please post the code of database connection …
just how to connect database using vc++.
actually i am new in visual c++…
and thanx for these topic .
these are really helpful.
Thanks
Thanks for this information is good and useful for me!
Ahmed,
Thanks for these code is very short code to check thread.
Неплохо