Search code examples
cpthreadsposix

Is it valid to call pthread_join on the main thread?


Is the behavior of this code well-defined?

#include <stdio.h>
#include <pthread.h>

pthread_t mt;

void *start(void *x)
{
    void *y;
    pthread_join(mt, &y);
    printf("joined main thread\n");
    return 0;
}

int main()
{
    pthread_t t;
    mt = pthread_self();
    pthread_create(&t, 0, start, 0);
    pthread_exit(0);
}

Solution

  • Yes, this is possible. Indeed, this possibility is one of the main reasons why pthread_detach() exists. From the POSIX docs for pthread_detach() (see man pthread_detach):

       It  has  been suggested that a "detach" function is not necessary; the
       detachstate thread creation attribute is sufficient,  since  a  thread
       need  never  be dynamically detached. However, need arises in at least
       two cases:
    
        1. In a cancellation handler for a pthread_join() it is nearly essen-
           tial  to  have  a pthread_detach() function in order to detach the
           thread on which pthread_join() was waiting. Without it,  it  would
           be  necessary  to  have  the  handler do another pthread_join() to
           attempt to detach the thread, which would both delay the cancella-
           tion  processing  for an unbounded period and introduce a new call
           to pthread_join(), which might itself need a cancellation handler.
           A dynamic detach is nearly essential in this case.
    
    
        2. In  order  to  detach the "initial thread" (as may be desirable in
           processes that set up server threads).
    

    So what you're proposing is fine according to the standards.

    Edit: Just to confirm that further, the POSIX description of exec() states:

    The initial thread in the new process image shall be joinable, as if created with the detachstate attribute set to PTHREAD_CREATE_JOINABLE.