5. (20 pts) Here is another trivial threaded program. Each thread simply prints
ID: 3751062 • 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
This is your final running code:
#include <stdio.h>
#include<pthread.h>
#include <semaphore.h>
sem_t mutex;
int main(){
sem_init(&mutex, 0, 1);
pthread_t thread1,thread2,thread3;
void *f1();
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);
sem_destroy(&mutex);
return 0;
}
void *f1(int x){
sem_wait(&mutex);
printf("%d ",x);
sem_post(&mutex);
}
This code will print numbers serially like1,2,3.
Used semaphores to wait so threads are created and executed sequencially.
If problem not solved you can add sleep(2); between creating threads so that excecution will always be sequencial.
Please upvote if it worked :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.