There is a producer, a consumer, and a shared buffer.
- The buffer has finite capacity, N items.
- Producer and consumer run simultaneously.
- From time to time, the producer puts an item into the buffer. If the buffer is full, the producer must wait.
- From time to time, the consumer takes an item out of the buffer. If the buffer is empty, the consumer must wait.
Thought process:
There are three distinct tasks:
- Need a way to block producers when the buffer is full.
- Need a way to block consumers when the buffer is empty.
- Need a critical section for accessing the buffer.
Use three semaphores:
- Semaphore 'full' is initialized to 0.
- Semaphore 'empty' is initialized to N.
- Semaphore 'mutex' is initialized to 1.
Solution:
1
2
3
4
| volatile Buffer buffer;
Semaphore empty = new Semaphore(N);
Semaphore full = new Semaphore(0);
Semaphore mutex = new Semaphore(1);
|
1
2
3
4
5
6
7
8
9
| void producer() {
while (true) {
empty.P();
mutex.P();
produce();
mutex.V();
full.V();
}
}
|
1
2
3
4
5
6
7
8
9
| void consumer() {
while (true) {
full.P();
mutex.P();
consume();
mutex.V();
empty.V();
}
}
|
Comments
Post a Comment