Question
semThreadUnnamed.c #include #include #include #include sem_t s; //a semaphore s //function prototype void* threadFunction(void* param); int main() { //initialize the unnamed semaphore s using: sem_init(&s,
semThreadUnnamed.c
#include
sem_t s; //a semaphore s
//function prototype void* threadFunction(void* param);
int main() { //initialize the unnamed semaphore s using: sem_init(&s, 0, 1); //&s is the pointer to the semaphore //0 means that this semaphore is shared by threads created by this process //1 sets the initial value of the semaphore to 1 sem_init(&s, 0, 1); pthread_t t0,t1; int tnumber = 0; pthread_create(&t0,NULL,threadFunction,&tnumber); sleep(2); //wait 2 seconds tnumber++; pthread_create(&t1,NULL,threadFunction,&tnumber); pthread_join(t0,NULL); pthread_join(t1,NULL); sem_destroy(&s); return 0; }
void* threadFunction(void* param) { int tnum; tnum = *((int *)param); sem_wait(&s); //can I access my critical section? (semWait()) //critical section printf(" Thread %d has enetered its CS.. ", tnum); printf(" Thread %d is executing in its CS.. ", tnum); sleep(4); printf(" Thread %d is leaving its CS.. ", tnum); sem_post(&s); //signal that the thread is leaving and the CS is free (semSignal()) pthread_exit(0); }
Examine the attached code in semThreadUnnamed.c. This code protects the critical section using an unnamed semaphore. The critical section in this example is simply a message. Compile the code using gcc semThreadUnnamed.c -o sem1 -lpthread -1rt The - Ipthread and -1rt links the pthreads and real-time modules. Execute with ./sem1 and observe the output. Submit a screenshot of the outputStep by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started