Reputation: 387
I'm trying to implement a multithreaded application but got some doubts. Can anybody please clarify one this?
My main goal is to
The program for this is:
for(i = 0; i < 5; i++)
{
pthread_create(tid[i], NULL, func, NULL)
}
Then generally we call for the pthread_join()
:
for(j = 0; j < 5; j++)
{
pthread_join(tid[j], NULL);
}
So here my question is that in this call of pthread_join()
, if thread 2 finishes first then thread 2 will wait for thread 1 to finish as we have put in a sequential loop for the pthread_join()
function.
Upvotes: 0
Views: 92
Reputation: 1
Your loop is not doing something magical. So it calls
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
pthread_join(tid[3], NULL);
pthread_join(tid[4], NULL);
in the above order.
If you want to join threads in some other order, you need to use explicitly some synchronizations inside your func
. You may want to use condition variables and mutexes. Read a good pthread tutorial
Upvotes: 2
Reputation: 464
When you use pthread_join() function in a loop, your system will wait until first thread is returned, then the second one and so on. If the second thread is finished, it will wait for the first one and then it will take care of the second one.
Upvotes: 1
Reputation: 30489
for(j=0; j< 5 ; j++)
{
pthread_join(tid[j], NULL);
}
Means wait for thread with tid[0]
to finish. If it is already finished, return immediately.
Then wait for thread with tid[1]
to finish. If it is already finished, return immediately and so on.
In short, this for loop will make sure, current (possibly main) thread would not exit before children thread.
Upvotes: 4
Reputation: 14718
The for-loop is executed sequentially,
for(j=0; j< 5 ; j++)
{
pthread_join(tid[j], NULL);
}
so regardless of which thread finishes first, the for-loop will wait for thread 0 first, and then thread 1 etc. If thread 2 actually completes first then the result of that thread will simply just hang around until the join is executed -- this is similar to the way the wait
call works if you were to wait for specific process ids.
Upvotes: 3