Semaphores Flashcards
Example: Vaccination by Locking
Lock allows only one in at a time: underutilization of booths
Example: Vaccination by Semaphore
Vaccination in Code
Selling tickets via Semaphore
What happens if
* Number of buyers and initial number of tickets are equal?
* There are zero tickets initially?
* Number of tickets is greater than the number of buyers?
Locks only provide mutual exclusion
– One thread executes in the critical section at a time
May want more threads using resources concurrently
* Produce/consumer problem
– Need one thread to run after the other
– Don’t wish to operate in lockstep
Semaphore Definition (Dijkstra, 1965)
A synchronization primitive implemented via a counter with a nonnegative initial value, and supports two operations that are guaranteed to be atomic:
- acquire:
If counter is positive, then decrement counter by 1 and let calling thread continue. If counter is 0, block the thread on the semaphore. - release:
Increment counter by 1. If there are blocked threads on
the semaphore, unblock some such thread.
acquire aka wait aka P aka down
release aka signal aka V or up
Note: Counter value is never negative!
Semaphore Psuedocode for Mutual Exclusion
How does this work?
Blocking/Unblocking Management
Internally managed by thread system
The thread system records the threads that are blocked on a semaphore. E.g., it may place them in a queue for the semaphore.
When semaphore is incremented, the system picks a thread from the queue to run.
The thread runs whenever it is scheduled!
Implementing Semaphores in Java
Each Java object O has an associated monitor M, with two conceptual components, a lock L and wait set W
- L ensures at most one thread in any code synchronized on O
- Recall: synchronized method() {body} in O
equiv. to. method(){synchronized(O){body}}
- W: maintains threads blocked on M.
- O.wait() suspends calling thread and adds it to W
- Can only be called from synchronized blocks
- Releases L
- O.notify() takes a thread from W and makes it runnable.
- Can only be called from synchronized blocks
- Thread must obtain L before resuming
- O.wait() suspends calling thread and adds it to W
Semaphores in Java (Buggy)
Semaphores in Java (Fixed)