Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!

How to Cancel a Thread

Jun
762
16
Because of an error in a script, I just launched a thread that I do not want (it's going to do something tomorrow rather than today). This made me realize that sometimes one might want to be able to kill a thread. Is there any way to do that?

My first thought was to have the thread report back its PID so that it could be killed, but I don't see any way to do that. Any other suggestions?

For this particular application, I probably could use DATEMONITOR, in which case the command could be used to cancel it.
 
A thread doesn't have a PID (it has a TID). Terminating a thread (by handle) is, in general, possible, but not recommended. A lot of cleanup stuff that you'd expect isn't done. When I've really needed this, I have built an escape mechanism into whatever I'm running in the thread ... a sentinel ... an environment variable or file that the thread checks.

An idea: if you're using one of the MONITOR* functions in the thread you could, from outside the thread, kill the monitor, though I'm not sure how the thread would know that you did that.

This might be of interest.
 
I was not doing anything complex, just delaying for a calculated time and then sounding a beep (mostly a simple alarm for timing my eyedrops). Because of a mistake in the script, I set an alarm for a time when I didn't want one, which is what made me think of the issue of deleting a thread. One extra beep was no big deal. DATEMONITOR would have worked for this application except that I'm timing down to the seconds level, and DATEMONITOR only resolves to hours and minutes (though I could, of course, round up to the next minute in most cases).
 
Back
Top