Question: This programming question is about semaphore . Please create two threads t1 and t2 . t1 and t2 share an integer data counter . The

This programming question is about semaphore.

Please create two threads t1 and t2. t1 and t2 share an integer data counter. The job of t1 is to increase the value of counter by 1 when t1 is scheduled. The job of t2 is to decrease the value of counter by 1 when t2 is scheduled.

Because counter is a critical section, you need to use semaphore to implement mutual exclusion between t1 and t2.

Here is the API you may use:

sem_init: initialize an unnamed semaphore

sem_wait: lock a semaphore, which is equivalent to the P operation.

sem_post: unlock a semaphore, which is equivalent to the V operation.

sem_destroy: destroy an unnamed semaphore.

Here is the basic structure of the program:

int counter; //shared between t1 and t2

main()

{

Create semaphore;

Create t1;

Create t2;

Destroy semaphore;

}

thread t1 routine()

{

while (1)

{

P();

Increase counter by 1;

Output the value of counter;

V();

}

}

thread t2 routine()

{

while (1)

{

P();

Decrease counter by 1;

Output the value of counter;

V();

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!