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]*/}
}
4
  • 4
    If your goal is to join all the threads anyway, why does matter that you're waiting for one longer than another? Commented Feb 10, 2015 at 4:12
  • 4
    Joining is waiting. Commented Feb 10, 2015 at 4:16
  • possible duplicate of Non-blocking pthread_join Commented Feb 12, 2015 at 8: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 ? Commented Oct 22, 2018 at 8:01

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.