0

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

chesschi
  • 666
  • 1
  • 8
  • 36
  • Is it possible that your thread just terminates on its own? In this case, `pthread_join()` returns the value returned by your thread functions. – sstn Mar 16 '15 at 10:13
  • @sstn: No because I added a print statement when it cancel the thread and another print statement in the else-statement of pthread_timedjoin_np. And the logs shows the thread is cancelled instead of terminating itself. – chesschi Mar 16 '15 at 11:17

0 Answers0