Link to home
Start Free TrialLog in
Avatar of carlosn
carlosn

asked on

Gracefull thread killing when App ends

My app will sometimes create a CWinThread-derived thread to go do some work.  It is technically a UI thread, since it has a window, used to monitor what is going on, but it does not get any user input.

I have the thread set up with the m_bAutoDelete to TRUE, so that once the tread is finished it deletes itself.  This works quite well until I try quitting the program while the thread is still running.  When this happens the thread gets killed, and memory leaks abound.

So I thought, when the app is quitting, I could somehow inform the thread that it is time to die.  However, because the thread can destroy itself, I don't know if I have a thread still running or not.  The thread destroys itself, but my pointer still has a value, alas one that is useless.

How can I figure out if the thread is still running when I quit, and if so tell it to quit before the app finishes?
Avatar of carlosn
carlosn

ASKER

Edited text of question
When you quit the application all threads of this will be automaticaly killed. Now your problem with memory leaks can be easily solved by only puting sleep(NNNN) in your WM_ONCLOSE member function of CFrmWnd Class. NNNN denotes milliseconds sleep(2000). That depends on your user interface thread. You try it out with changing the values of NNN and see in debug mode whether  your user interface thread is giving any memory leak or not. Please keep updating the interaction.
Avatar of carlosn

ASKER

I thought about doing this, but I would like some option that is a bit more graceful.  I'd rather not have an absolute wait, especially since most of the time the thread is already dead anyway.  The issue is only when the user happens to kill the app during the brief time the thread is running.
ASKER CERTIFIED SOLUTION
Avatar of mikeblas
mikeblas

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of carlosn

ASKER

I see what you are getting at here.  I hadn't thought of that approach.  My only concern, if the thread deletes itself after completion, there isn't a handle to wait on any more.  Say I had a thread pointer 'pThread'

The thread executed, and then deleted itself because of the m_bAutoDelete = TRUE.  What happens if I try a WaitOnSingleEvent(pThread->m_hThread);  It seems that there is a slim chance that whatever happens to lie in the memory once occupied by the variable could point to a waitable object, though I guess that is fairly slim.

Carlos
In actuality, there is.  The thread handle is valid until someone calls CloseHandle() on it.

The CWinThread object, on the other hand, can delete itself as you describe. And, for that reason, m_bAutoDelete is of dubious value in the class.

B ekiM