Lecture 12: Synchronization 3 - Semaphores Flashcards
Goals for Solving Critical Sections
- Mutual Exclusion
no more than 1 process in its critical section at a time - Progress
cannot keep postponing scheduling process into its critical section if no other is in its critical section - Bounded wait
once a process requests entering critical section, there must be a bound on # of other processes allowed to enter their critical section before granted
Clever Algorithms
- Strict Alternation
- After You
- Peterson’s Algorithm
Strict Alternation
Threads take turns entering C/S
Mutex? Yes
Progress? No
Bounded-wait? Yes
After You
Threads enter C/S when no others want to
Mutex? Yes
Progress? No
Bounded-wait? No
Peterson’s Algorithm
Combines Strict Alternation and After You algorithms. Thread enters C/S when its turn, or thread whose turn it is not interested
Mutex? Yes
Progress? Yes
Bounded-wait? Yes
Disabling Interrupts
+: Easy to see that it works
–: Overkill
- Disables all interrupts (e.g.: I/O)
- Disallows concurrency with threads in non- critical sections
–: Doesn’t work for multicore systems
(Each CPU has own interrupts: threads on different
CPU’s can access their critical sections at same time)
Test and Set
- New AL instruction (∴ Atomic)
- Can be used to implement “locking”
Semaphores
Data structure consisting of lock with wait queue
Semaphore variations
Binary Semaphore: one thread can hold lock at a time (n = 1) good for critical sections
Counting Semaphore:n threads can hold lock at a time (good for other synchronization problems)
Binary Semaphores and Critical Sections: Why so much simpler than Peterson’s algorithm?
• devil is in the details
must ensure that no two threads can execute acquire, release on
same semaphore at the same time (shared counter, cnt)
• C/S Problem moved to semaphore implementation! Will Revisit After Talking About Monitors
Bounded-Buffer Problem
- Shared variable
buffer [N]: shared by all
in: shared by all producers
out: shared by all consumers - Full buffer:
ensure that producer doesn’t try and insert into (instead wait until not full) - Empty buffer:
ensure that consumer doesn’t try to consume from (instead wait until not empty)
Bounded Buffer Problem: Use of Semaphores
- mutex
• binary (initialized to 1)
• ensures exclusive access to code reading, writing in, out, buffer - empty
• counting (initialized to buffer size, N)
• when = 0, no empty slots. Begins queueing producers - full
• counting (initialized to 0)
• when = 0, no full slots. Begins queueing consumers