The goal of this assignment is to write a multithreaded program that explores sy
ID: 3803597 • Letter: T
Question
The goal of this assignment is to write a multithreaded program that explores synchronization challenge. For this part, assume that, we have a shared variable NextID. This is initialized to 1 at the beginning.
Now create 5 threads in your program and assign ID 1,2,3,4,5 to them respectively. You can pass the ID as a parameter when you create the threads.
Each of the threads will try to access the variable “NextID”.
Whenever a thread acquires the variable, it checks whether the NextId is equal to its own Id or not.
If it is not equal, it will output “Not My Turn!”, then print its threadId, and then release the variable.
If it is equal, the thread will print “My turn!”, then print its threadId, increase the NextId by 1, and then release the variable. However, after increasing NextID by 1, the thread will check if the value is 6 or not. If it is 6, it will reset it to 1 before releasing the variable.
The program should execute until each thread prints “Mu Turn!” 20 times. Once a thread prints for 20 times, it terminates.
Count the number of times each thread prints “Not my Turn!” and include that in the report.
Code should be in C
Explanation / Answer
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int NextID = 1, total1 = 0, total2 = 0, total3=0, total4 = 0, total5 =0;
void *myThreadFun(void *vargp)
{
int myid = (int)vargp;
if(NextID == myid)
{
printf("My Turn %d ", myid);
switch(NextID)
{
case 1: total1++; break;
case 2: total2++; break;
case 3: total3++; break;
case 4: total4++; break;
case 5: total5++; break;
}
NextID++;
if(NextID == 6)
NextID = 1;
}
else
{
printf("Not My Turn %d ", myid);
}
return NULL;
}
int main()
{
pthread_t tid1;
pthread_t tid2;
pthread_t tid3;
pthread_t tid4;
pthread_t tid5;
printf("Starting... ");
while(total1 <20 || total2 < 20 || total3<20 || total4<20 || total5<20)
{
pthread_create(&tid1, NULL, myThreadFun, (void*)1);
pthread_create(&tid2, NULL, myThreadFun, (void*)2);
pthread_create(&tid3, NULL, myThreadFun, (void*)3);
pthread_create(&tid4, NULL, myThreadFun, (void*)4);
pthread_create(&tid5, NULL, myThreadFun, (void*)5);
}
printf("Finishing.. ");
exit(0);
}
OUTPUT:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.