Stopping a Thread


#1

Hey there,
I’ve recently come across a bug in a crate which caused a nasty infinite loop, so in trying to fix it I tried to build a test case, which isolates the code in a thread and waits for a second to see if it has finished.
Is there a way to kill a long running child-thread in the stdlib?

cheers


Limit execution time of test?
#2

There is no way to kill a thread from the outside.
There exists the option to send a signal, but it will invoke whatever signal handler is installed for the process and thus might kill the whole process, not just a single thread (this is valid for *nix).

If possible, you would need the thread itself checking for some external trigger.
Otherwise, your best option is probably to launch a full process, which you can then kill.


#3

There are OS-dependent ways to do this. On UNIX, you can get the handle via std::os::unix::thread::JoinHandleExt and call libc::pthread_cancel. On Windows, you can get the handle via std::os::windows::thread::JoinHandleExt and call kernel32::TerminateThread


#4

Oh, hm, why did I not see that before?
In Hoodie’s case it’s probably ok, though in a general case this should be used with care.


#5

Thanks, I looked in the libc doc and found pthread_kill, though that seems to cover the same cases.
Actually gave me the chance to read up on the libc itself a little bit. :smiley:


Limit execution time of test?
#6

Not sure if that’s what you want, from the pthread_kill manpage:

NOTES
       Signal dispositions are process-wide: if a signal handler is installed,
       the handler will be invoked in the thread _thread_, but if  the  disposi‐
       tion  of  the signal is "stop", "continue", or "terminate", this action
       will affect the whole process.