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

后端 未结 5 1437
深忆病人
深忆病人 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:29

    you could keep a list all your thread ids and then do pthread_join on each one, of course you will need a mutex to control access to the thread id list. you will also need some kind of list that can be modified while being iterated on, maybe a std::set?

    int main() {
       pthread_mutex_lock(&mutex);
    
       void *data;
       for(threadId in threadIdList) {
          pthread_mutex_unlock(&mutex);
          pthread_join(threadId, &data);
          pthread_mutex_lock(&mutex);
       }
    
       printf("All threads completed.\n");
    }
    
    // called by any thread to create another
    void CreateThread()
    {
       pthread_t id;
    
       pthread_mutex_lock(&mutex);
       pthread_create(&id, NULL, ThreadInit, &id); // pass the id so the thread can use it with to remove itself
       threadIdList.add(id);
       pthread_mutex_unlock(&mutex);  
    }
    
    // called by each thread before it dies
    void RemoveThread(pthread_t& id)
    {
       pthread_mutex_lock(&mutex);
       threadIdList.remove(id);
       pthread_mutex_unlock(&mutex);
    }
    

提交回复
热议问题