Reputation: 4533
I have an exam tomorrow on OS. And i have doubts with couple of the previous year questions.... I am not good with C
Explain why the code below is not optimal for concurrency. and how the code can be optimized..
void * func ( void * arg)
{
printf("printing from thread %d\n",(int) arg);
return null;
}
int main(void)
{
pthread_t threads[5];
int i;
for(i=0;i<5;i++)
{
pthread_create( &(thread[i]), NULL, func, (void*) i);
pthread_join( threads[i], NULL);
}
return 0;
}
Second....
really appreciate any help.....
Upvotes: 0
Views: 8118
Reputation: 182639
In the first snippet you shouldn't join in the for
. Joining right after creation will prevent concurrency: basically you have only one thread at any time and you're waiting for it. Join outside instead:
for(i = 0; i<5; i++)
pthread_create(&thread[i], NULL, func, (void*) i);
for(i = 0; i < 5; i++)
pthread_join(threads[i], NULL);
Looking a third time at the second snippet it's apparent that the following can happen:
Since no progress can be made, it's a deadlock.
Upvotes: 2
Reputation: 409176
For the first question, you do not start five threads to run simultaneous, instead you create one thread and wait for it to exit before you start the next.
For the second question, think about what happens if the thread locks the mutex first before the main function does it.
Upvotes: 0