How can I reliably end a thread?

My program uses two threads. One of them is created whenever I click an item in a listbox and does some processing before exiting.

I want to be able to end the second thread if it is already running when I click a different item in the listbox.

One thing I tried is having the second thread continue processing as long as some boolean value is true and then setting that value to false whenever the listbox selection changes. I would then use WaitForSingleObject() before re-creating the thread. This causes my program to hang most of the time.

What else can I do besides using TerminateThread()?
did you wait for the 2nd object to destroy ( use http://msdn.microsoft.com/en-us/library/windows/desktop/ms683190%28v=vs.85%29.aspx )? Also dont use " some boolean" but windows events.

Also:
If there is always one working thread, why closing it? Just suspend it and wakeup when it has something to do.
One thing I tried is having the second thread continue processing as long as some boolean value is true and then setting that value

You can't synchronise threads using boolean values, you have to use a synchronization object; in this case, and Event.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms686364(v=vs.85).aspx

I don't know what your thread is doing, but you can communicate with it using synchronization object from the main thread. It's up to you to decide because only you know what it's doing.
Thanks, this has been very helpful. So I will re-think how my thread function works and use events to synchronize. Out of curiosity though, why can't you use booleans to synchronize?
why can't you use booleans to synchronize?
Because the management of normal variables isn't atomic, so you get race conditions (different results depending on the result of some race of two unsynchronised things).

You have to syn concurrent processes/threads using suitable atomic objects.
Topic archived. No new replies allowed.