Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For pthread, How to kill child thread from the main thread

Tags:

I use pthread_create to create several child threads. At a time, the main thread wants to kill all child threads or there will be segment falut. Which function should I use to finish that? I searched the answer from google and got function like pthread_kill. But I did not know which signal should I send to the child thread to kill them. My running environment is RHEL 5.4 and programming language is C.

like image 311
terry Avatar asked Sep 29 '10 14:09

terry


2 Answers

In general, you don't really want to violently kill a child thread, but instead you want to ask it to terminate. That way you can be sure that the child is quitting at a safe spot and all its resources are cleaned up.

I generally do this with a small piece of shared state between parent and child to allow the parent to communicate a "quit request" to each child. This can just be a boolean value for each child, protected by a mutex. The child checks this value periodically (every loop iteration, or whatever convenient checkpoints you have in your child thread). Upon seeing "quit_request" being true, the child thread cleans up and calls pthread_exit.

On the parent side, the "kill_child" routine looks something like this:

acquire shared mutex
set quit_request to true 
pthread_join the child 

The pthread_join may take some time, depending on how frequently the child checks its quit request. Make sure your design can handle whatever the delay may be.

like image 86
Bill Gribble Avatar answered Sep 18 '22 20:09

Bill Gribble


It is possible to "cancel" a thread using pthread_cancel. However, this isn't typically best practice though under extreme circumstances like a SEGFAULT it may be conisdered a reasonable approach.

like image 36
torak Avatar answered Sep 18 '22 20:09

torak