Is it safe to call pthread_cancel() on terminated thread?

There is a hint actually:

ERRORS top

  ESRCH  No thread with the ID thread could be found.

And MKS gives a bit other description:

ESRCH

thread does not specify a currently running thread in the process.

OpenGroup recommends:

If an implementation detects use of a thread ID after the end of its lifetime, it is recommended that the function should fail and report an [ESRCH] error.

UPDATE

in NPTL there is a check for double cancel or cancel after exit:

  /* We are canceled now.  When canceled by another thread this flag
     is already set but if the signal is directly send (internally or
     from another process) is has to be done here.  */
  int newval = oldval | CANCELING_BITMASK | CANCELED_BITMASK;

  if (oldval == newval || (oldval & EXITING_BITMASK) != 0)
    /* Already canceled or exiting.  */
    break;

So, second cancel or cancel after exit will be a noop for dead thread.

The exiting_bitmask is set by __do_cancel:

/* Called when a thread reacts on a cancellation request.  */
static inline void
__attribute ((noreturn, always_inline))
__do_cancel (void)
{
  struct pthread *self = THREAD_SELF;

  /* Make sure we get no more cancellations.  */
  THREAD_ATOMIC_BIT_SET (self, cancelhandling, EXITING_BIT);

__do_cancel is both reaction to async cancel and to pthread_exit

void
__pthread_exit (value)
     void *value;
{
  THREAD_SETMEM (THREAD_SELF, result, value);

  __do_cancel ();

I think it needs to be safe, or pthread_cancel would be problematic (next to unusable).

Indeed, if it wouldn't be safe, every call to pthread_cancel would have to be enormously complicated by checking the thread is alive (and ensuring it stays alive until you get to cancel it). A simple "are you still there" wouldn't do.

In conclusion, I believe pthread_cancel must be safe if the thread has terminated. Of course, this might not be the case for a terminated and joined thread.

Tags:

C

Posix

Pthreads