Algo-Sim › Concurrency
Producer–Consumer with wait and notifyAll
Medium · Concurrency · step through it in Java, Python and C++ on your own input
A monitor-based bounded buffer with one producer and two consumers. notifyAll wakes everyone, so each woken thread must re-check its condition in a while loop.
Problem
Write a bounded Buffer with put(x) and take() using one lock (a monitor) and wait/notifyAll instead of semaphores. A producer puts 1, 2, …, items; consumer 1 takes ⌈items/2⌉ of them and consumer 2 the rest. slice is how many calls a thread makes before the scheduler moves on. Return the items in the order they were taken.
Constraints
- 1 ≤ capacity ≤ 3, 1 ≤ items ≤ 6
- Use while, not if, around wait()
- Items leave in the order they were put
Edge cases to test
- Every consumer waiting on an empty buffer
- The buffer full with the producer waiting
- A wake-up meant for another thread
Follow-up questions
- Why
notifyAllinstead ofnotify? - With one condition shared by producers and consumers,
notifymay wake the wrong kind of thread and deadlock. - What would you use in production?
- A library queue such as
ArrayBlockingQueueor Python’squeue.Queue, which handle this correctly.
Solution
Java
class Buffer {
private final Deque<Integer> items = new ArrayDeque<>();
private final int capacity;
Buffer(int capacity) {
this.capacity = capacity;
}
public synchronized void put(int x) throws InterruptedException {
while (items.size() == capacity) wait();
items.addLast(x);
notifyAll();
}
public synchronized int take() throws InterruptedException {
while (items.isEmpty()) wait();
int x = items.pollFirst();
notifyAll();
return x;
}
}Python
import threading
from collections import deque
class Buffer:
def __init__(self, capacity):
self.items = deque()
self.capacity = capacity
self.cond = threading.Condition()
def put(self, x):
with self.cond:
while len(self.items) == self.capacity:
self.cond.wait()
self.items.append(x)
self.cond.notify_all()
def take(self):
with self.cond:
while not self.items:
self.cond.wait()
x = self.items.popleft()
self.cond.notify_all()
return xC++
#include <bits/stdc++.h>
using namespace std;
class Buffer {
deque<int> items;
int capacity;
mutex m;
condition_variable changed;
public:
explicit Buffer(int capacity)
: capacity(capacity) {}
void put(int x) {
unique_lock<mutex> lock(m);
changed.wait(lock, [&] { return int(items.size()) < capacity; });
items.push_back(x);
changed.notify_all();
}
int take() {
unique_lock<mutex> lock(m);
changed.wait(lock, [&] { return !items.empty(); });
int x = items.front();
items.pop_front();
changed.notify_all();
return x;
}
};
More Concurrency problems
- Print in Order (Easy)
- Print FooBar Alternately (Medium)
- Design Bounded Blocking Queue (Medium)
- Read–Write Lock (Medium)