When spinning a new thread I am doing few things which that thread needs to consume. If something is wrong I want to cancel, or exit from that thread. I read that pthread_exit does not do resource clean up. So I like to stick with pthread_cancel. Question is can I call pthread_cancel on the same thread. I am aware that I can call pthread_cancel from some other thread but not sure from its own thread. (How to kill a running thread?) What is the best way to do this?
My code looks like below.
void* my_thread(){
//do this --> go to failure if fails
//do that --> go to failure if fails
//do this too --> go to failure if fails
while(1){
//will read, write or usleep until data is available
}
failure:
pthread_cancel(my_thread_id);
}
CodePudding user response:
Question is can I call pthread_cancel on the same thread.
There is no documented restriction against it, so I expect pthread_cancel(thread_id)
to have the same effect when called from a thread whose ID is thread_id
as it does when called from any other thread.
However, "the same effect" can be no effect if the thread has cancellation disabled, and it can be a deferred (until the next cancellation point) effect if the thread's cancellation type is PTHREAD_CANCEL_DEFERRED
(the default). To have the greatest likelihood of terminating the thread, as quickly as possible, you should:
// ensure that the thread is cancellable
int old_state;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state);
// perform the cancellation
pthread_cancel(my_thread_id);
// user-defined cancellation point
pthread_testcancel();
With that said, the question seems to be based on a faulty premise:
I read that pthread_exit does not do resource clean up.
That is exactly as true of pthread_cancel()
as it is of pthread_exit()
. Thread termination by either of those means will cause any registered cancellation handlers to be invoked, which does provide a route for resource cleanup, but neither does any cleanup of process-shared resources other than that.*
Thread cancellation is almost always the wrong thing to do. It is especially the wrong thing for a thread to do to itself, as pthread_exit()
is cleaner, safer, and more reliable, and the two have the same cleanup semantics. You do have to take appropriate measures to clean up resources, but that's true either way. pthread_cancel()
does not provide any unique shortcuts for that.
* Note: unlike termination via pthread_cancel()
or pthread_exit()
, returning from the entry-point function does not cause cancellation handlers to run.