Let's say I have a thread which I need to be able to terminate at any given point and do it safely as possible.

Currently I am doing it by calling TerminateThread and including all possible kernel32 calls inside the thread inside a critical section so the termination function wont destroy it when a kernel call is made - ala crash. The termination function frees all resources that might been allocated by the thread and it works fine, however I am curious if this approach is any good.I was thinking about using a variable instead of critical sections which could be checked once a while and depending on it's status thread will terminate itself. Both solution look a bit dirty to me. In 1st there is a need to wrap hundreds of calls with critical sections. 2nd requires checking the variable every few instructions (i need the thread to be able to terminate as soon as the termination function has been called).

What kind of processing work does the thread do? Are there any regular points (in a loop or so) where you enter a waiting state, like reading data from a file or from a network socket? Or do you process data in chunks where you could perform a test once in, say, 1000 iterations?

If there's only one thread, you can use a simple flag variable in the global data.If there's multiple threads, use two variables: one is a flag to acknowledge that a thread wishes to die, and the other contains the handle (or index of handle) of the thread we wish to terminate.No matter what you do, you are going to have to poll something, I just wanted to point out that we can eliminate the api call from regular loop iteration within the thread, we just have to take more responsibility within the thread to poll such flags.

arafel, you can use event-based notification of socket data, then - this is one of the more efficient socket models anyway. Instead of just waiting on the socket event, you add a "thread must terminate" event as well, and check for that.

Hi there,what I did some time ago was to just close the reading socket from the main thread and let the reading thread terminate on a socket error ... In another tool I also called WSACleanup from the main thread and made the only thread terminate on sock err again.