xmllmx
xmllmx

Reputation: 42255

What if a being-waited thread detaches itself?

#include <pthread.h>

void thread_routine(void*)
{
    sleep(5);
    pthread_detach(pthread_self());
    sleep(5);
}

int main()
{
    pthread_t t;
    pthread_create(&t, 0, thread_routine, 0);
    pthread_join(t);
}

Will pthread_join(t); return immediately after pthread_detach(pthread_self()); succeed?

Upvotes: 2

Views: 421

Answers (2)

pilcrow
pilcrow

Reputation: 58534

The behavior is undefined, and thus obviously to be avoided at all costs.

(As far as I can tell the behavior is implicitly undefined. There are several kindred instances of explicitly undefined behavior in the spec, but this exact scenario is not mentioned.)

For the curious, on an NPTL Linux system near me, both the pthread_detach() and the pthread_join() return 0, and, moreover, the latter blocks and successfully gets the value returned by the thread. On an OS X system near me, by contrast, the pthread_detach() succeeds, and the pthread_join() immediately fails with ESRCH.

Upvotes: 4

David Schwartz
David Schwartz

Reputation: 182763

Your code is buggy. By the time you call pthread_join, the thread may already have terminated. Since it's detached, the pthread_t is not longer valid. So your code may pass an invalid pthread_t to pthread_join, which can cause unpredictable behavior.

To avoid these kinds of problems one specific thing should control the lifetime of a thread. That can be the thread itself, if it's detached, in which case no thread should try to join it. It can also be the thread that joins it, in which case the thread should not be detached.

Upvotes: 1

Related Questions