John
John

Reputation: 4533

Concurrency in Threads

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....

enter image description here

really appreciate any help.....

Upvotes: 0

Views: 8118

Answers (2)

cnicutar
cnicutar

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);

EDIT (thanks R..)

Looking a third time at the second snippet it's apparent that the following can happen:

  • The parent tries locks the mutex, signals the child and goes on to unlock and join. But the child is not waiting on the condition variable and the signal is lost.
  • The child eventually locks the mutex and starts waiting.

Since no progress can be made, it's a deadlock.

Upvotes: 2

Some programmer dude
Some programmer dude

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

Related Questions