5.6 semaphores semaphores –software construct that can be used to enforce mutual exclusion...

4
5.6 Semaphores • Semaphores – Software construct that can be used to enforce mutual exclusion – Contains a protected variable • Can be accessed only via wait and signal commands • Also called P and V operations, respectively

Post on 19-Dec-2015

232 views

Category:

Documents


0 download

TRANSCRIPT

5.6 Semaphores

• Semaphores– Software construct that can be used to

enforce mutual exclusion– Contains a protected variable

• Can be accessed only via wait and signal commands

• Also called P and V operations, respectively

5.6.1 Mutual Exclusion with Semaphores

• Binary semaphore: allow only one thread in its critical section at once– Wait operation

• If no threads are waiting, allow thread into its critical section

• Decrement protected variable (to 0 in this case)• Otherwise place in waiting queue

– Signal operation• Indicate that thread is outside its critical section• Increment protected variable (from 0 to 1)• A waiting thread (if there is one) may now enter

Figure 5.15 Mutual exclusion with semaphores.

5.6.1 Mutual Exclusion with Semaphores

Group Discussion 5 (2/12/2009)

Questions 1-3 are related to the code of figure 5.15.

1. If Occupied is 1, can the calling thread go into its critical section?

2. What happens if the initial value of the semaphore is set to 0?

3. If a thread did not call P before V, what happens?

4. Is there any advantage for using semaphores vs. TestAndSet instruction?

5. Does TestAndSet provide mutual exclusion?