Canceling a thread without any collaboration with the thread itself is not possible. The TerminateThread () API function is suitable only during a process shutdown. Yes, you could make QueueUserAPC () work too, but it still requires thread collaboration. It should block the wait descriptor and explicitly signal its warning (bAlertable argument, say WaitForSingleObjectEx).
Making it warning requires a lot of effort in your code because of the asynchronous nature of the QUA callback. You must make sure that you are not leaking any resources used by the thread when the mat is suddenly popped out from under it. Pretty hard to do, the callback has little context to correctly guess what needs to be cleared. If you do not make the stream available in only a few places.
But, while the thread needs to make a blocking call and can only be accessed in a few places, you can also use WaitForMultipleObjects (). Adding an event that signals the termination of a stream. Cancellation will now be carried out synchronously, cleaning is much easier.
You can use a wait call with a zero timeout inside the main loop of the thread if it is never blocked. This is quite expensive due to the cache. Use volatile bool if you don't care too much about response time. You should not, in any case, this is not very deterministic.
source share