Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

posix

pthreads

I'm wondering if it is safe to call pthread_cancel() on a terminated thread. I couldn't find any hints in the manual page. Thanks in advance for any hints.

Edit: Maybe I wasn't accurate enough. I'm not talking about threads terminated by an earlier pthread_cancel() but about threads that simply returned from their thread function.

like image 463
domachine Avatar asked Aug 29 '11 20:08

domachine


2 Answers

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.

like image 63
cnicutar Avatar answered Sep 21 '22 17:09

cnicutar


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 ();
like image 29
osgx Avatar answered Sep 23 '22 17:09

osgx