Search code examples
clinuxmultithreadingpthreadsposix-api

How can I wait for any/all pthreads to complete?


I just want my main thread to wait for any and all my (p)threads to complete before exiting.

The threads come and go a lot for different reasons, and I really don't want to keep track of all of them - I just want to know when they're all gone.

wait() does this for child processes, returning ECHILD when there are no children left, however wait does not (appear to work with) (p)threads.

I really don't want to go through the trouble of keeping a list of every single outstanding thread (as they come and go), then having to call pthread_join on each.

As there a quick-and-dirty way to do this?


Solution

  • The proper way is to keep track of all of your pthread_id's, but you asked for a quick and dirty way so here it is. Basically:

    • just keep a total count of running threads,
    • increment it in the main loop before calling pthread_create,
    • decrement the thread count as each thread finishes.
    • Then sleep at the end of the main process until the count returns to 0.

    .

    volatile int running_threads = 0;
    pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER;
    
    void * threadStart()
    {
       // do the thread work
       pthread_mutex_lock(&running_mutex);
       running_threads--;
       pthread_mutex_unlock(&running_mutex);
    }
    
    int main()
    {
      for (i = 0; i < num_threads;i++)
      {
         pthread_mutex_lock(&running_mutex);
         running_threads++;
         pthread_mutex_unlock(&running_mutex);
         // launch thread
    
      }
    
      while (running_threads > 0)
      {
         sleep(1);
      }
    }