Algo-Sim › Concurrency

Design Bounded Blocking Queue

Medium · Concurrency · step through it in Java, Python and C++ on your own input

A fixed-size queue shared by a producer and a consumer. enqueue blocks while the queue is full and dequeue while it is empty, using one semaphore for free places and one for filled places.

Problem

Implement a thread-safe bounded queue with enqueue(element), which blocks while the queue is full, dequeue(), which blocks while it is empty, and size(). Here a producer thread enqueues 1, 2, …, produce and a consumer thread dequeues consume times; slice is how many calls a thread makes before the scheduler switches. Return size() after both finish.

Constraints

Edge cases to test

Follow-up questions

Semaphores or a lock with conditions?
Two semaphores count free and filled slots; a lock with notFull and notEmpty conditions also works and makes size checks easier.
Why is a mutex still needed with semaphores?
With several producers or consumers, the array and indices must be updated by one thread at a time.

Solution

Java

import java.util.concurrent.Semaphore;

class BoundedBlockingQueue {
    private final Deque<Integer> queue = new ArrayDeque<>();
    private final Semaphore slots;                          // free places
    private final Semaphore items = new Semaphore(0);       // filled places

    public BoundedBlockingQueue(int capacity) {
        slots = new Semaphore(capacity);
    }

    public void enqueue(int element) throws InterruptedException {
        slots.acquire();
        synchronized (queue) { queue.addLast(element); }
        items.release();
    }

    public int dequeue() throws InterruptedException {
        items.acquire();
        int x;
        synchronized (queue) { x = queue.pollFirst(); }
        slots.release();
        return x;
    }

    public int size() {
        synchronized (queue) { return queue.size(); }
    }
}

Python

import threading
from collections import deque


class BoundedBlockingQueue:
    def __init__(self, capacity):
        self.queue = deque()
        self.lock = threading.Lock()
        self.slots = threading.Semaphore(capacity)   # free places
        self.items = threading.Semaphore(0)          # filled places

    def enqueue(self, element):
        self.slots.acquire()
        with self.lock:
            self.queue.append(element)
        self.items.release()

    def dequeue(self):
        self.items.acquire()
        with self.lock:
            x = self.queue.popleft()
        self.slots.release()
        return x

    def size(self):
        with self.lock:
            return len(self.queue)

C++

#include <bits/stdc++.h>
using namespace std;
// C++17 counting semaphore: a predicate handles spurious wakeups.
class Semaphore {
    mutex m;
    condition_variable ready;
    int permits;

  public:
    explicit Semaphore(int n)
        : permits(n) {}
    void acquire() {
        unique_lock<mutex> lock(m);
        ready.wait(lock, [&] { return permits > 0; });
        --permits;
    }
    void release() {
        {
            lock_guard<mutex> lock(m);
            ++permits;
        }
        ready.notify_one();
    }
};
class BoundedBlockingQueue {
    deque<int> queue;
    Semaphore slots, items{0};
    mutex queueMutex;

  public:
    explicit BoundedBlockingQueue(int capacity)
        : slots(capacity) {}
    void enqueue(int element) {
        slots.acquire();
        {
            lock_guard<mutex> lock(queueMutex);
            queue.push_back(element);
        }
        items.release();
    }
    int dequeue() {
        items.acquire();
        int x;
        {
            lock_guard<mutex> lock(queueMutex);
            x = queue.front();
            queue.pop_front();
        }
        slots.release();
        return x;
    }
    int size() {
        lock_guard<mutex> lock(queueMutex);
        return int(queue.size());
    }
};

More Concurrency problems