The following code shows that I try to cancel the thread when the start_routine
is not completed within the time ts
, and join the thread to make sure the thread to terminate. I have used this on a simple function for start_routine
and res2
returns PTHREAD_CANCELED
. However, I tried to use this approach for calling third party library in start_routine
and this does not return PTHREAD_CANCELED
(i.e. I got "pthread is terminated due to xxx?").
pthread_create(&thread, &attr, start_routine, (void *)&arg);
if (0 != pthread_timedjoin_np(thread, &res1, &ts)
{
if (0 == pthread_cancel(thread))
{
if (0 == pthread_join(thread, &res2))
{
if (PTHREAD_CANCELED == res2)
{
std::cout << "pthread is cancelled" << std::endl;
}
else
{
std::cout << "pthread is terminated due to xxx?" << std::endl;
}
}
}
}
According to the manpage of pthread_join
:
If the target thread was canceled, then PTHREAD_CANCELED is placed in *retval.
What are the possible return values of pthread_join
when using pthread_cancel
? Why pthread_join
sometimes does not return PTHREAD_CANCELED
?
Please note that I used the default cancel type (i.e. PTHREAD_CANCEL_DEFERRED
) and enable cancel (i.e. PTHREAD_CANCEL_ENABLE
).