0

I got the following scenario with a concurrency problem, implemented using pthread library:

I got a thread that might be cancelled at any time. When that thread is cancelled, it needs to cancel its child thread, and make sure its child thread is already cancelled before it terminates.

So I end up with calling pthread_join twice on the child thread, once in the thread routine (as when the thread is not cancelled, I need that result), once in the thread's cancellation cleanup handler.

However, pthread_join doesn't allow joining the same thread twice, so what will happen?

Below is pseudo code:

void CleanupFunc(void* ChildThread)
{
    pthread_cancel(*(pthread_t*)ChildThread);
    pthread_join(*(pthread_t*)ChildThread, NULL);
}

void* ThreadFunc(void* _)
{
    pthread_t ChildThread;
    pthread_cleanup_push(&CleanupFunc, &ChildThread);
    pthread_create(&ChildThread, NULL, &ChildThreadFunc, NULL);
    pthread_join(ChildThread, NULL);
    pthread_cleanup_pop(0);
}

Thanks in advance!

A.Stone
  • 137
  • 1
  • 9
  • "*I need that result*" from the code you show, it does not look like you need it: `pthread_join(ChildThread, NULL);` – alk Apr 11 '17 at 11:29
  • Cancelling a thread is mostly never a good idea. You might want to overthink you program's design. – alk Apr 11 '17 at 11:31

1 Answers1

0

However, pthread_join doesn't allow joining the same thread twice, so what will happen?

The thread is no longer joinable, so the result is undefined behavior.

Per the POSIX standard documentation for pthread_join():

The behavior is undefined if the value specified by the thread argument to pthread_join() does not refer to a joinable thread.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
  • So can I assume one of the pthread_join calls will work? Is the one in the cleanup handler going to work? – A.Stone Apr 09 '17 at 14:23
  • @A.Stone No, you can't assume it will work. It almost certainly will *not* work, and even if it appears to work, you may have just joined some random other thread. You might even wind up with [nasal demons](http://www.catb.org/jargon/html/N/nasal-demons.html). – Andrew Henle Apr 09 '17 at 14:25
  • But there're only two pthread_join, right? Does it means the first one will work, and (I think) the one in the cleanup handler is the first one? After the cleanup handler finished, the thread will terminate, and the second pthread_join won't have effect. But that's my guess, how do you think? Or do you have some better ways to achieve what I want to do? – A.Stone Apr 09 '17 at 14:30