Reputation: 17459
I use pthread_create(&thread1, &attrs, //... , //...);
and need if some condition occured need to kill this thread how to kill this ?
Upvotes: 49
Views: 123412
Reputation: 5172
There are two approaches to this problem.
sigaction()
which sets a flag, and the thread periodically checks the flag to see whether it must terminate. When the thread must terminate, issue the signal to it using pthread_kill()
and wait for its termination with pthread_join()
. This approach requires pre-synchronization between the parent thread and the child thread, to guarantee that the child thread has already installed the signal handler before it is able to handle the termination signal;pthread_cancel()
and wait for its termination with pthread_join()
. This approach requires detailed usage of pthread_cleanup_push()
and pthread_cleanup_pop()
to avoid resource leakage. These last two calls might mess with the lexical scope of the code (since they may be macros yielding {
and }
tokens) and are very difficult to maintain properly.(Note that if you have already detached the thread using pthread_detach()
, you cannot join it again using pthread_join()
.)
Both approaches can be very tricky, but either might be specially useful in a given situation.
Upvotes: 29
Reputation: 3804
I agree with Antti, better practice would be to implement some checkpoint(s) where the thread checks if it should terminate. These checkpoints can be implemented in a number of ways e.g.: a shared variable with lock or an event that the thread checks if it is set (the thread can opt to wait zero time).
Upvotes: 6
Reputation: 25522
First store the thread id
pthread_create(&thr, ...)
then later call
pthread_cancel(thr)
However, this not a recommended programming practice! It's better to use an inter-thread communication mechanism like semaphores or messages to communicate to the thread that it should stop execution.
Note that pthread_kill(...) does not actually terminate the receiving thread, but instead delivers a signal to it, and it depends on the signal and signal handlers what happens.
Upvotes: 76