Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Windows API similar to pthread_cancel?

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?

like image 950
Jay Avatar asked Feb 28 '23 20:02


2 Answers

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.

like image 135
Hans Passant Avatar answered Mar 05 '23 02:03

Hans Passant

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.

like image 29
JesperE Avatar answered Mar 05 '23 02:03