OS 15 - Semaphores PDF
OS 15 - Semaphores PDF
Semaphores
1
Outline
● Definition of semaphores
● Binary semaphores (Locks)
● Semaphores for ordering
● The producer/consumer (bounded buffer) problem
● Reader-writer locks
● The dining philosophers
● Thread Throttling
● Implement semaphores
2
Semaphore ( lit. 'apparatus for signalling'; from Ancient Greek σῆμα
(sêma) 'mark, sign, token', and Greek -φόρος (-phóros) 'bearer,
carrier') is the use of an apparatus to create a visual signal transmitted
over distance…
– Wikipedia (https://en.wikipedia.org/wiki/Semaphore )
3
Overview
4
Semaphore: definition
6
Binary semaphores
7
Binary semaphores (conti.)
8
Binary semaphores (conti.)
9
Semaphores for ordering
10
Semaphores for ordering (conti.)
What should the initial value of this semaphore be?
11
Semaphores for ordering (conti.)
12
Semaphores for ordering (conti.)
13
Setting the value of a semaphore
14
The producer/consumer (bounded
buffered) problem
15
First attempt
Let MAX = 1
16
First attempt
Let MAX = 10
→ race
condition
17
A solution:
adding mutual
exclusion
→ deadlock
18
Avoiding deadlock
→ move the mutex acquire and release to be just around
the critical section
19
Reader-writer locks
20
21
The dining philosophers
22
The dining philosophers (conti.)
23
24
Thread throttling
● How can a programmer prevent “too many” threads from doing
something at once and bogging the system down?
Answer: decide upon a threshold for “too many”, and then
use a semaphore to limit the number of threads concurrently
executing the piece of code in question.
→ throttling, and consider it a form of admission control
● A simple semaphore can solve this problem.
○ Initializing the value of the semaphore to the maximum number of threads
○ Put a sem_wait() and sem_post() around the admission controlled
region → a semaphore can naturally throttle the number of threads that are
ever concurrently in the dangerous region of the code
25
Implement semaphores
26
Implement semaphores (conti.)
27
Summary
28