- Semaphore: an integer variable
S
which can only be accessed through
two atomic operations: wait
and
signal
.
(Note: Tanenbaum calls these DOWN
and UP
.
Originally Dijstra, the inventer, called them P
and
V
.)
- Implementation of semaphores with busy waiting
wait(int *SP): signal(int *SP):
while (*SP <= 0) ; *SP = *SP + 1;
*SP = *SP - 1;
Remember: these are atomic.
- Example 1:
int S;
while (1) {
wait(&S);
critical section
signal(&S);
}
- How should S be initialized?
- What if it is initialized to 0? --- No one gets in.
- What if it is initialized to 1?
- What if it is initialized to 10?
- Example 2:
Suppose we have two concurrent processes and process 1 must execute
S1
before process 2 executes S_2
.
Process 1 executes:
S1;
signal(&sync);
Process 2 executes:
wait(&sync);
S2;
How should sync
be initialized?
- Example 3: When a process uses more than
one semaphore, a deadlock can occur.
That is, the process will never return from the wait.
Consider two processes P1 and P2 executing the following code:
P_1 code:
wait(&S);
...
signal(&Q);
P_2 code:
wait(&Q);
...
signal(&S);
S
and Q
are initialized
to 0.
- Three classical problems in synchronization
- Producer-consumer (unbounded)
- Bounded buffer problem
- Assume a pool of n buffers each of which can contain one item.
- Use three semaphores:
mutex
, empty
and full
.
- The
mutex
semaphore is initialized to 1.
- The
empty
and full
semaphores count the number of empty and full buffers.
They are initialized to n and 0.
- Reader-writer problem (4 variations)
Consider a shared file in which some processes need to only read, but others
may need to update (read and write).
- Strong reader preference - this one done in text
No reader will be kept waiting unless a writer has already obtained
permission to write.
That is, no reader will be kept waiting because a writer is waiting.
This problem may have starvation of writers.
- Strong writer preference - this one is harder
Once a writer is waiting, it gets to write as soon as possible.
That is, new readers must wait if a writer is waiting.
This problem may have starvation of readers.
- Weak reader preference - Readers can continue to get
in as long as a reader is reading, but when no one is accessing,
the next access is selected on a FIFO basis.
- Weak writer preference - Readers can continue to
get until a writer is next in line.