Question

Please write a multi-thread program using Pthreads library. In this problem, 10 thread should be created...

Please write a multi-thread program using Pthreads library. In this problem, 10 thread should be created and the counter integer variable is shared among threads and initialized by 0.

In addition, each thread executes an infinite loop which keeps increasing the counter value by 1 and prints counter and thread id values in each iteration

0 0
Add a comment Improve this question Transcribed image text
Answer #1

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

int counter= 0;

void *myThreadFun(void *vargp)
{
   int *myid = (int *)vargp;

   while(1)
   {
   printf("Thread ID: %d, Counter Value : %d\n", *myid,++counter);
   }
}

int main()
{
   int i;
   pthread_t tid;

   for (i =1; i <=10; i++)
   {   pthread_create(&tid, NULL, myThreadFun, (void *)&i);
   }
  
   for (i =1; i <=10; i++)
   {   pthread_join(tid,NULL);
   }
   pthread_exit(NULL);
   return 0;
}

////USE THIS CODE FOR CHECKING THE CORRECTNESS OF OUTPUT (RUN MULTIPLE TIMES TO SEE ALL ///THREADS INVOLVED IN RUNNING

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

int counter= 0;

void *myThreadFun(void *vargp)
{
   int *myid = (int *)vargp;

   while(counter<300)
   {
   printf("Thread ID: %d, Counter Value : %d\n", *myid,++counter);
   }
}

int main()
{
   int i;
   pthread_t tid;

   for (i =1; i <=10; i++)
   {   pthread_create(&tid, NULL, myThreadFun, (void *)&i);
   }
  
   for (i =1; i <=10; i++)
   {   pthread_join(tid,NULL);
   }
   pthread_exit(NULL);
   return 0;
}

Add a comment
Know the answer?
Add Answer to:
Please write a multi-thread program using Pthreads library. In this problem, 10 thread should be created...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT