Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Cleanup if Thread Fails to Close - C++

When my application is ready to close the tread it created using CreateThread the following algorithm is executed:

_bCloseRequested = TRUE;
dwMsThen = ::GetTickCount();

do
{
    ::GetExitCodeThread( m_hThread, &dwExitCode );
    dwMsNow = ::GetTickCount();
}
while( (dwExitCode == STILL_ACTIVE) && ((dwMsNow - dwMsThen) < 50000UL) );

If the thread fails to close within the 5 allotted seconds, should the thread handle be closed, or allowed to remain open? Thanks.

like image 931
Jim Fell Avatar asked Jan 22 '23 01:01

Jim Fell


1 Answers

First, don't wait for a thread to finish like this. You will eat up all available CPU time just waiting, which has also the disadvantage that your thread will take longer to finish!

Use something like this instead:

WaitForSingleObject(m_hThread, 50000);

That said: whether you want to leave the thread running or not depends on what the thread does. Can it even run even though your main app starts doing something else? Does it have critical stuff (files, connections, databases, ...) open that would be left open if you kill the thread? You have to consider all of this before you decide whether to kill the thread or leave it running.

like image 140
Stefan Avatar answered Jan 23 '23 16:01

Stefan