Re: Stopping a thread
scyle wrote:
Many times, it happens that a thread is blocked in a blocking function call,
like a sever waiting on accept.
So how do you terminate such a thread?
One way is to avoid uninterruptible waits, using functions like
WSAEventSelect instead of accept. In general, the best approach is to
carefully design a thread so that it is "terminateable". In the future,
we may see the addition of "cancellation" to Win32, where you can cancel
a thread, which will cause an exception to be thrown by the current or
next blocking Win32 or CRT function to be called in the thread. However,
a thread will still need to be designed to be "cancel-safe", in other
words, designed to handle these exceptions.
Using TerminateThread() is an option but it is not recommended, since it
doesn't clear the stack, free the critical sec... and many more problems!
So is there a way to terminate the thread tidily?
Only really if it is designed for termination. For example, a thread
that is in the middle of a long Sleep call is hard to terminate
gracefully, so you should avoid sleep calls, and instead wait on a
termination event with a timeout.
In general, creating a termination event for each worker thread is a
good idea, and any time it needs to block, it should wait on that event
as well as any other events. E.g. use OVERLAPPED IO, and event
notification versions of functions with WaitForMultipleObjects.
Tom