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.