Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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,

image text in transcribed

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, 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 output

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Beginning Apache Cassandra Development

Authors: Vivek Mishra

1st Edition

1484201426, 9781484201428

More Books

Students also viewed these Databases questions

Question

Can knowledge workers and/or professionals be performance-managed?

Answered: 1 week ago

Question

Ability to work comfortably in a team environment

Answered: 1 week ago