C11 : killing a thread using standard-only library

84 views Asked by At

How does one go about killing a thread in C using the functions provided in <threads.h>? There seems to be no direct way of doing this. Note: I'm aware that pthreads provides a pthread_cancel() function but I would like to stick to <threads.h> functions.

1

There are 1 answers

0
Siguza On

You can't.

It's trivial to enumerate the 8 functions defined by the C11 standard for <threads.h>, iterate through them and determine that none of them does what you want.

Therefore, as written, your requirements cannot be met. If that is all you care about, then you can stop reading here.


If you care about practical solutions, then it depends on what actual problem you're trying to solve:

  • If you have a thread stuck somewhere in code that you wrote, then you simply add an _Atomic variable and check it repeatedly. This is pretty much what pthread_cancel is doing anyway.
  • If you have a thread stuck somewhere in code that you call into but have no control over, then you need existing synchronisation points. If the code you call into uses the syscalls that pthread_cancel declares to be synchronisation points, then you can use that. If not, then you'll have to make use of preemption and that goes into OS-specific territory. On POSIX systems, you can mask a given signal on all threads except the target, and when that signal is raised, it will by necessity be raised on the target thread. Lower-level APIs might exist to remove threads from the scheduling pool and clean up their kernel state, but that will not clean up their userland state. And despite your claim that, in your case, they are "not using resources", there will at the very least be a stack to clean up, and very likely also thrd_*-API bookkeeping data.
  • If you have a thread stuck in kernel mode, then there is absolutely nothing you can do. There is no god, not even SIGKILL will save you, no kernel could ever sanely recover from killing a thread with an active call stack in the kernel, all you can do is pull the power chord.