views:

165

answers:

2

Is there a Windows native API analogous to pthread_cancel, pthread_testcancel etc?

If not, how can we simulate cancelling of one thread from another using the pthread_cancel mechanism in Windows?

+1  A: 

The Pthreads/win32 FAQ talks about this under question 9, "Cancelation doesn't work for me, why?". The FAQ mentions the Pthreads library using a packages called "QueueUserAPCEx" in order to achieve true asynchronous user-mode notifications. It isn't clear from your question if you are using Pthreads/win32, but you may find some hints and implementation details in the Pthreads/win32 source code.

JesperE
I am not using pthreads/win32. I am using windows native APIs.
Jay
+4  A: 

Canceling a thread without any cooperation from the thread itself is not possible. The TerminateThread() API function is only suitable during process shutdown. Yes, you could make QueueUserAPC() work too but that still requires the thread's cooperation. It has to block on a wait handle and explicitly signal that it's alertable (the bAlertable argument to, say, WaitForSingleObjectEx).

Making it alertable requires lots of effort in your code due the asynchronous nature of the QUA callback. You have to make sure that you don't leak any resources used by the thread when the rug is suddenly pulled out from under it. Pretty hard to do, the callback has little context available to guess correctly what needs to be cleaned up. Unless you make the thread alertable in only a few places.

But, as long as the thread has to make a blocking call and can only be alertable in a few places, you might as well use WaitForMultipleObjects(). Adding an event that signals the thread to stop. The cancellation will now by synchronous, clean-up is much easier.

You can use a wait call with a zero timeout inside a thread's main loop if it never blocks. That's fairly expensive due to the cache flush. Use a volatile bool if you don't care too much about response time. You shouldn't, it isn't very deterministic anyway.

Hans Passant
Incase of pthreads, the cleanup part is made easy by pthread_push.. and pthread_pop.. set of APIs. Is there no such mechanism available in Windows?
Jay
The cleanup I'm talking about is releasing resources. Freeing memory, closing files, closing handles. That's not automatic in C/C++.
Hans Passant