[Operating System] Producer - Consumer Problem

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:
  1. Need a way to block producers when the buffer is full.
  2. Need a way to block consumers when the buffer is empty.
  3. Need a critical section for accessing the buffer.
Use three semaphores:
  1. Semaphore 'full' is initialized to 0.
  2. Semaphore 'empty' is initialized to N.
  3. 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

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee