views:

116

answers:

3

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.

+3  A: 

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.

torak
A: 

You should send SIG_TERM to each of your threads, using

  int pthread_kill(pthread_t thread, int sig);

A quick way to get rid of all threads (besides the main) is to fork() and keep going with the child.
Not hyper clean...

  if (fork()) exit(0); // deals also with -1...
ring0
+4  A: 

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.

Bill Gribble