5. (20 pts) Here is another trivial threaded program. Each thread simply prints
ID: 3751063 • Letter: 5
Question
5. (20 pts) Here is another trivial threaded program. Each thread simply prints the value of the passed argument (ignore compiler warnings; we are abusing the argument pointer to pass an integer) Enter this program and run it a bunch of times. You' notice that the order of thread execution is random Without changing main), use semaphores to enforce that threads always get executed in order, so that what is printed are the values 1, 2, and 3, in that order include include int maino pthread t thread, thread, thread3 void 11O pthread create(kthread1, NULL.f1.1) pthread_create (kthread2, NULL, f 1,2); pthread create(kthread3,NULL,f1,3) pthread.join(thread1, NULL) pthread-join(thread2· NULL); pthread join(thread3, NULL) return 0 void .f1 int x)( print"dla, x)i pthread exit(o)Explanation / Answer
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define NUMBER_TH 3
sem_t t1, t2, mutex;
int counter = 0, cycle= 0;
int main()
{
pthread_t thread1, thread2, thread3;
void *f1();
sem_init(&t1, 0, 0);
sem_init(&t2, 0, 1);
sem_init(&mutex, 0, 1);
pthread_create(&thread1,NULL,f1,1);
pthread_create(&thread2,NULL,f1,2);
pthread_create(&thread3,NULL,f1,3);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
return 0;
}
void *f1(int x)
{
while(cycle < NUMBER_TH)
{
//meet here
sem_wait(&mutex);
counter++;
if(counter == NUMBER_TH)
{
sem_wait(&t2);
sem_post(&t1);
}
sem_post(&mutex);
sem_wait(&t1);
if(cycle + 1 == x)
{
printf("%d ", x);
cycle++;
}
sem_post(&t1);
sem_wait(&mutex); //again meet here
counter--;
if(counter == 0)
{
sem_wait(&t1);
sem_post(&t2);
}
sem_post(&mutex);
sem_wait(&t2);
sem_post(&t2);
}
pthread_exit(0);
}
Output of program:-
1
2
3
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.