My application creates a thread and that runs in the background all the time. I can only terminate the thread manually, not from within the thread callback function.
At the moment I am using TerminateThread()
to kill that thread but it's causing it to hang sometimes.
I know there is a way to use events and WaitForSingleObject()
to make the thread terminate gracefully but I can't find an example about that.
Please, code is needed here.
Since you don't know what the thread is doing, there is no way to safely terminate the thread from outside.
Why do you think you cannot terminate it from within?
You can create an event prior to starting the thread and pass that event's handle to the thread. You call
SetEvent()
on that event from the main thread to signal the thread to stop and thenWaitForSingleObject
on the thread handle to wait for the thread to actually have finished. Within the threads loop, you callWaitForSingleObject()
on the event, specifying a timeout of0
(zero), so that the call returns immediately even if the event is not set. If that call returnsWAIT_TIMEOUT
, the event is not set, if it returnsWAIT_OBJECT_0
, it is set. In the latter case you return from the thread function.I presume your thread isn't just burning CPU cycles in an endless loop, but does some waiting, maybe through calling
Sleep()
. If so, you can do the sleeping inWaitForSingleObject
instead, by passing a timeout to it.What are you doing in the background thread? If you're looping over something, you can end the thread within itself by having a shared public static object (like a
Boolean
) that you set totrue
from the foreground thread and that the background thread checks for and exits cleanly when set totrue
.TerminateThread is a bad idea, especially if your thread uses synchronization objects such as mutexes. It can lead to unreleased memory and handles, and to deadlocks, so you're correct that you need to do something else.
Typically, the way that a thread terminates is to return from the function that defines the thread. The main thread signals the worker thread to exit using an event object or a even a simple boolean if it's checked often enough. If the worker thread waits with
WaitForSingleObject
, you may need to change it to aWaitForMultipleObjects
, where one of the objects is an event. The main thread would callSetEvent
and the worker thread would wake up and return.We really can't provide any useful code unless you show us what you're doing. Depending on what the worker thread is doing and how your main thread is communicating information to it, it could look very different.
Also, under [now very old] MSVC, you need to use
_beginthreadex
instead ofCreateThread
in order to avoid memory leaks in the CRT. See MSKB #104641.Update:
One use of worker thread is as a "timer", to do some operation on regular intervals. At the most trivial:
Another use is to do something on-demand. Basically the same, but with the timeout set to
INFINITE
and doing some action onWAIT_OBJECT_0
instead ofWAIT_TIMEOUT
. In this case you would need two events, one to make the thread wake up and do some action, another to make it wake up and quit:Note that it's important that the loop do something reasonable if WFSO/WFMO return an error instead of one of the expected results. In both examples above, we simply treat an error as if we had been signaled to quit.
You could achieve the same result with the first example by closing the event handle from the main thread, causing the worker thread get an error from
WaitForSingleObject
and quit, but I wouldn't recommend that approach.It is a code example for thread management in the fork-join manner. It use struct Thread as a thread descriptor.
Let's introduce some abstraction of the thread descriptor data structure:
Functions for the thread parent use:
StopThread() initiate thread termination and wait until thread will be actually terminated.
This set of functions is expected to be used from the thread launched by StartThread():
First function can be used for light-weight checks for termination request during long-running job processing. (For example big file compression). Rest of the functions handle the case of waiting for some system resources, like events, semaphores etc. (For example worker thread waiting new request arriving from the requests queue).