Lecture 13: Synchronization 5: Dining+Monitors Flashcards
Semaphores Variations
- Binary semaphore
2. Counting semaphore:
Binary semaphore
(resource count of 0/1, available/unavailable)
-one thread can hold lock at a time (n = 1)
good for critical sections
Counting semaphore
(resource count of n)
n threads can hold lock at a time (good for other synchronization problems)
Dining Philosopher
Solution 1
Goal: Ensure only one philosopher grabs a given chopstick at a time
Solution 1: Array of binary semaphores
Dining Philosophers
Solution 2
Idea: Ensure only one philosopher grabs both of his chopstick at a time
Solution 2: Make grabbing chopsticks a critical section (i.e., add binary semaphore, mutex)
Dining Philosophers
Solution 3
Idea: Rather than synchronizing on chopsticks & their availability, synchronize on
-philosophers & their “state” (HUNGRY, THINKING, EATING) Philosophers declare themselves to be hungry, & wait for
neighbors to finish eating
Solution 3:
- Array of philosopher “states” (state [0 … n-1])
- Array of philosopher (binary) semaphores (phil [0 … n-1])
Software Abstraction 1: Semaphores
-Useful Abstraction of HW Primitives (Lock + Wait Queue)
Software Abstraction 1: Semaphores Pro
simple to implement conceptually simple
Software Abstraction 1: Semaphores Con
-still low-level
- some synchronization solutions very tricky with semaphores: (e.g., R/W (writers-favored))
sometimes used in unintuitive ways
• e.g, bounded buffers – FULL, EMPTY semaphores not used as locks (initialized to 0)
Software Abstraction 2: Monitors
- A high-level synchronization abstraction
- Objects with built-in, thread-at-a-time access
wait()
- blocks thread + releases lock
- it checks the interruption status of thread − throws exception if true.
When thread t calls …
a. t releases object lock
b. t’s state = BLOCKED
c. t placed in wait set
notify()
-wakes thread blocked on object
When thread t calls …
a. selects some thread t’ from wait list
b. moves t’ to entry set
c. state of t’:= RUNNABLE (Can again compete for lock)