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

后端 未结 5 1433
深忆病人
深忆病人 2020-12-08 07:15

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\'

5条回答
  •  死守一世寂寞
    2020-12-08 07:40

    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);
      }
    }
    

提交回复
热议问题