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

Edge cases to test

Follow-up questions

Why notifyAll instead of notify?
With one condition shared by producers and consumers, notify may wake the wrong kind of thread and deadlock.
What would you use in production?
A library queue such as ArrayBlockingQueue or Python’s queue.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 x

C++

#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