2

Say the main thread created three worker threads. Suppose all three threads run a function similar to work() below.

bool signal[3]={false};

void* work(void* thread_id)  //each worker thread is given a thread_id when created
{
    int x = *(int*)thread_id;
    int data;
    /*code*/
    signal[x] = true;  //this thread finished
    pthread_exit(&data);
}

Usually I use following code to join the threads.

int main()
{
    pthread_t workerThreads[3];
    int master;
    /* code for creating threads */
    for(int i=0;i<3;i++)
    { 
        void* status;
        master = pthread_join(workerThreads[i],&status);
        /* code for handling the return data from thread*/
    }  
}

What I mean is if workerThreads[2] finished before workerThreads[0] , with the code above, main thread still have to wait for workerThreads[0] finish first before handling workerThreads[2]

Is there a way to join the threads without waiting?

Can I use something like this?

while(!signal[0]||!signal[1]||!signal[2]){
if(signal[0]){/*join workerThreads[0]*/}
if(signal[1]){/*join workerThreads[1]*/}
if(signal[2]){/*join workerThreads[2]*/}
}
smwikipedia
  • 61,609
  • 92
  • 309
  • 482
Sasino
  • 69
  • 2
  • 8
  • 4
    If your goal is to join *all* the threads anyway, why does matter that you're waiting for one longer than another? – Barry Feb 10 '15 at 04:12
  • 4
    Joining *is* waiting. – n. m. could be an AI Feb 10 '15 at 04:16
  • possible duplicate of [Non-blocking pthread\_join](http://stackoverflow.com/questions/73468/non-blocking-pthread-join) – alk Feb 12 '15 at 08:54
  • Do you want to wait only until **one** of the threads finishes(the first that finishes), or do you still want to wait until **all** threads are finished ? – nos Oct 22 '18 at 08:01

0 Answers0