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.
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)