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

前端 未结 4 859
误落风尘
误落风尘 2021-02-08 00:45

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.

<
4条回答
  •  被撕碎了的回忆
    2021-02-08 00:47

    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 ();
    

提交回复
热议问题