Producer-Consumer
The problem involves two threads: a producer and a consumer. The producer inserts data into a buffer, and the consumer extracts data from that buffer. The buffer has a predefined size, so:
- The producer cannot insert data if the buffer is full.
- The consumer cannot extract data if the buffer is empty.
- The producer and consumer cannot act on the buffer simultaneously.
A correct implementation of the problem ensures that there will be no deadlock situations, meaning situations where the two threads are waiting for each other with no possibility of unblocking.
This problem can be solved in various ways (solutions are provided above in the text of the laboratory):
- Using semaphores
- Using condition variables
Pseudocode - solutions using semaphores:
T[] buffer = new T[k];
semaphore gol(k);
semaphore plin(0);
mutex mutex;
producer(int id) {
T v;
while (true) {
v = produce();
gol.acquire();
mutex.lock();
buf.add(v);
mutex.unlock();
plin.release();
}
}
consumer(int id) {
T v;
while (true) {
plin.acquire();
mutex.lock();
v = buf.poll();
mutex.unlock();
gol.release();
consume(v);
}
}