Search code examples
cmultithreadingunixpthreadspthread-join

What if thread exit before other thread wait for it(join)?


For example, If I create 3 threads and join them in the same order. If the second thread exit first, then what would happen to the pthread_join. Will the program block until tid1 exits or directly return from pthread_join(&tid2,NULL)?

   pthread_t tid1,tid2,tid3;
   pthread_create(&tid1, NULL, SomeFun, NULL);
   pthread_create(&tid2, NULL, SomeFun, NULL);
   pthread_create(&tid3, NULL, SomeFun, NULL);
   pthread_join(&tid1, NULL);
   pthread_join(&tid2, NULL);
   pthread_join(&tid3, NULL);

Solution

  • when you code calls:

    pthread_join(&tid1, NULL);
    

    if tid1 has not exited yet, then that call will block until it does. if tid2 exits in the meantime, that doesn't change the behavior of this particular call. But in that scenario, when the call does return, the next call:

    pthread_join(&tid2, NULL);
    

    will return immediately since the tid2 has already exited.

    If you want to immediately perform some work when an arbitrary thread is finished, you'll need to use something other than pthread_join() to synchronize with the "some thread is finished" event. Perhaps waiting on a condition variable that gets signaled by every thread when they complete (along with some mechanism such as a queue so the waiting thread can determine which thread has signaled completion). Another mechanism that could be used is to have threads write information to a pipe that the main (or controlling) thread reads to get that notification.