I use pthread_create(&thread1, &attrs, //... , //...);
and need if some condition occured need to kill this thread how to kill this ?
views:
1298answers:
3
+4
A:
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.
antti.huima
2010-01-18 09:03:36
The problem with pthread_cancel, btw, is that if you use it, then the code running in the thread that's cancelled, has to understand cancellation points, and make sure that (a) it hits one frequently enough that it actually gets cancelled in good time, and (b) it doesn't leak resources when this happens. This is kind of tricky, whereas if you use a message, then it's nicely explicit in your code exactly when the thread can exit.
Steve Jessop
2010-01-18 11:07:56
+1
A:
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).
Fredrik Jansson
2010-01-18 09:06:43