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

前端 未结 4 860
误落风尘
误落风尘 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:59

    Yes, it is safe to call it before pthread_detach or pthread_join has been called. However, according to my experiments, it can return ESRCH (=3) if the thread has already returned from its thread function. (gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0)

    #include "gtest/gtest.h"
    
    static void *S_ThreadEntry1(void* pvarg)
    {
         return 0;
    }
    
    TEST(ThreadTest, PthreadCancelAfterExit)
    {
         pthread_t threadid;
         ASSERT_EQ(pthread_create(&threadid, 0, &S_ThreadEntry1, nullptr), 0);
         sleep(1);
    
         int cancel_ret = pthread_cancel(threadid);
         std::cout << "pthread_cancel returned " << cancel_ret << std::endl;
         if (cancel_ret != 0)
              EXPECT_EQ(cancel_ret, ESRCH);
         void* res;
         EXPECT_EQ(pthread_join(threadid, &res), 0);
         std::cout << "res=" << res << std::endl;
    }
    

    Output:

    [ RUN      ] ThreadTest.PthreadCancelAfterExit
    pthread_cancel returned 3
    res=0
    [       OK ] ThreadTest.PthreadCancelAfterExit (1000 ms)
    

提交回复
热议问题