Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pthread_kill doesnt kill thread C linux

i am making a small project which will be incorporated into larger project. basically what it does is keeps track of threads that are created by way of adding them to a main struct which keeps track of what the thread does (its main function) and its pthread_t id. the other struct keeps track of the data to be passed to the function and the element number of where the pthread_t id is stored inside threads[]. its a bit micky mouse and it jumps around a bit but it all works besides when it is time to kill the thread. i get no segfaults and no errors and the program finishes fine, but the thread does not get killed when pthread_kill() is called (the function returns 0 meaning no error and it worked) although the thread continues to run until the main application returns.

like image 945
randy newfield Avatar asked Mar 29 '26 22:03

randy newfield


1 Answers

pthread_kill() will not kill a thread. The only difference with kill() is that the signal is handled by the designated thread and not handled while that thread has the signal masked (see pthread_sigmask()). A signal like SIGTERM will by default still terminate the entire process.

If you are considering to call pthread_exit() from a signal handler, you should probably use pthread_cancel() instead.

Cancellation is safe if all code that may be cancelled cooperates (or the code that calls it disables cancellation for the time). Most libraries do not care about this, though.

A safer method is to ask the thread to exit without any force, such as by sending a special message to it (if the thread normally processes messages).

Alternatively, don't bother to kill any threads and just call _exit(), _Exit() or quick_exit().

like image 190
jilles Avatar answered Apr 02 '26 12:04

jilles