Title: Operating Systems
1OperatingSystems
CIS 432April 3, 2008
- David Goldschmidt, Ph.D.
- Computer Science
- The College of Saint Rose
2Semaphores
- A semaphore is a synchronization mechanism
provided by many operating systems - Semaphore S is a special integer variable
- Two atomic operations on S
- wait(S) or P(S)
- signal(S) or V(S)
3Semaphores
- The wait(S) operation decrementssemaphore S only
if possible - wait(S) while ( S lt 0 ) / no-op
/ S--
P1
wait(S)
S 1
wait(S)
wait(S)
P2
P3
Drawback here is busy waiting,which wastes CPU
cycles
4Semaphores
- The signal(S) operationincrements semaphore S
- signal(S) S
P1
wait(S)
S 1
wait(S)
wait(S) // CRITICAL // SECTION signal(S)
P2
P3
5Binary Semaphores
- A binary semaphore providesmutual exclusive
accessto a shared resource - Initialize semaphore S to 1
- Use wait(S) and signal(S)
P1
wait(S)
S 1
wait(S)
wait(S) // CRITICAL // SECTION signal(S)
P2
P3
6Counting Semaphores
- A counting semaphore controls access to afinite
number of instances of a given resource - e.g. access to open files, network
connections, shared buffers, etc. - Use wait(S) and signal(S) operations aswith
binary semaphores
// n instances of finite resource semaphore S n
Write pseudocode for theproducer-consumer
problem usingsemaphores to synchronize accessto
the shared buffer of size N
7Deadlock
- A deadlock occurs when every processis waiting
on another process - Deadlock might occur when using multiple
semaphores
semaphore S, Q
// P0 ... wait(S) wait(Q) ... signal(S) signal(Q)
...
// P1 ... wait(Q) wait(S) ... signal(Q) signal(S)
...
Deadlock!
8Starvation
- Starvation occurs when a processwaits
indefinitely as other processesuse shared
resources - Also known as indefinite blocking
9Dining Philosophers Problem
- Five philosophers sit at a table
- Each philosophereither thinks or eats
- To eat, a philosopher must pickup the closest
two chopsticks - But a philosopher may onlypick up one chopstick
at a time - Represents the problem of allocating several
resourcesto several processes without deadlock
or starvation
10Dining Philosophers Problem
N 5 philosopher( int i ) while (true)
think() pickUp(i) pickUp((i1)N)
eat() drop(i) drop((i1)N)
11Dining Philosophers Problem
semaphore chopstick 1, 1, 1, 1, 1
N 5 philosopher( int i ) while (true)
think() wait(chopsticki)
wait(chopstick(i1)N) eat() // CRITICAL
SECTION signal(chopsticki)
signal(chopstick(i1)N)
Is deadlock possible?
Write pseudocode to solvethe dining
philosophersproblem using semaphores
12Reading Assignments
- Read for next week
- Chapters 7 and 8 of the Dinosaur Book