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]*/}
}