Programming Search⌘K

Patterncore

Producer-consumer

Also called producer-consumer, producer-consumer problem, bounded buffer, bounded-buffer problem.

Producers put items into a shared buffer and consumers take them out. A bounded buffer makes a producer wait when it is full and a consumer wait when it is empty, so neither side runs too far ahead.

Family
concurrency
Intent
Join threads that make data to threads that use it through a buffer, so that each side runs at its own speed and a bounded buffer limits how far the producers get ahead.
Also called
Bounded buffer

Intent

Couple a producer and a consumer through a buffer. Dijkstra describes the producer as a cyclic process that produces a portion of information in each cycle, and the consumer as a cyclic process that processes the next portion in each cycle.1 The buffer lets the two run at different speeds.

Problem

The producer and the consumer are separate threads, and they share the buffer. If the buffer has unbounded capacity, the producer can be arbitrarily far ahead of the consumer, but the consumer can never be ahead of the producer.2 A fast producer then fills memory with items that nobody uses yet. A consumer that finds the buffer empty must wait, and it must not take the same item as another consumer.

Solution

Use a buffer of finite size, say N portions. Then the relation becomes symmetric: the consumer produces and the producer consumes empty positions in the buffer.2 Dijkstra's solution uses three semaphores:21

  • "number of queuing portions" counts the filled places. It starts at 0, and a consumer waits on it when the buffer is empty.21
  • "number of empty positions" counts the empty places. It starts at N, and a producer waits on it when the buffer is full.1
  • "buffer manipulation" starts at 1 and works as a mutex for the put and get operations.1
producer --put--> [ item | item | item | .... ]  N places --take--> consumer
          waits when full                       waits when empty

Modern libraries give the whole buffer as one type. A Java BlockingQueue supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available when storing an element.3 BlockingQueue implementations are designed to be used primarily for producer-consumer queues.3

Example

The example has 2 producers that each put 500 numbers into a buffer of 4 places, and 2 consumers that take them out. When the producers finish, the main thread puts one end-of-stream object for each consumer.

items consumed: 1000
sum of items: 499500
each item consumed once: True

The examples for each language show the same program.

PythonGitHub
import queue
import threading

DONE = object()  # the end-of-stream object
buffer = queue.Queue(maxsize=4)  # put blocks when 4 items wait
consumed = []
lock = threading.Lock()


def producer(start):
    for item in range(start, start + 500):
        buffer.put(item)


def consumer():
    while True:
        item = buffer.get()  # get blocks when the buffer is empty
        if item is DONE:
            return
        with lock:
            consumed.append(item)


producers = [threading.Thread(target=producer, args=(s,)) for s in (0, 500)]
consumers = [threading.Thread(target=consumer) for _ in range(2)]
for t in producers + consumers:
    t.start()
for t in producers:
    t.join()
for _ in consumers:
    buffer.put(DONE)  # one end-of-stream object for each consumer
for t in consumers:
    t.join()

print("items consumed:", len(consumed))
print("sum of items:", sum(consumed))
print("each item consumed once:", sorted(consumed) == list(range(1000)))
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: stdlib. queue.Queue(maxsize=4) is the bounded buffer: put waits when it is full and get waits when it is empty.
#include <algorithm>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <mutex>
#include <numeric>
#include <optional>
#include <thread>
#include <vector>

class BoundedBuffer {
public:
    explicit BoundedBuffer(size_t capacity) : capacity_(capacity) {}

    void put(int item) {
        std::unique_lock<std::mutex> lock(mutex_);
        not_full_.wait(lock, [this] { return items_.size() < capacity_; });
        items_.push_back(item);
        not_empty_.notify_one();
    }

    std::optional<int> take() { // empty result: the stream has ended
        std::unique_lock<std::mutex> lock(mutex_);
        not_empty_.wait(lock, [this] { return closed_ || !items_.empty(); });
        if (items_.empty()) return std::nullopt;
        int item = items_.front();
        items_.pop_front();
        not_full_.notify_one();
        return item;
    }

    void close() {
        std::lock_guard<std::mutex> lock(mutex_);
        closed_ = true;
        not_empty_.notify_all();
    }

private:
    size_t capacity_;
    std::deque<int> items_;
    bool closed_ = false;
    std::mutex mutex_;
    std::condition_variable not_full_, not_empty_;
};

int main() {
    BoundedBuffer buffer(4);
    std::mutex consumed_mutex;
    std::vector<int> consumed;

    std::vector<std::thread> producers, consumers;
    for (int start : {0, 500}) {
        producers.emplace_back([&buffer, start] {
            for (int item = start; item < start + 500; item++) buffer.put(item);
        });
    }
    for (int i = 0; i < 2; i++) {
        consumers.emplace_back([&] {
            while (auto item = buffer.take()) {
                std::lock_guard<std::mutex> lock(consumed_mutex);
                consumed.push_back(*item);
            }
        });
    }
    for (auto& t : producers) t.join();
    buffer.close(); // the end of the stream for every consumer
    for (auto& t : consumers) t.join();

    std::sort(consumed.begin(), consumed.end());
    std::vector<int> expected(1000);
    std::iota(expected.begin(), expected.end(), 0);
    long long sum = std::accumulate(consumed.begin(), consumed.end(), 0LL);
    std::cout << "items consumed: " << consumed.size() << "\n";
    std::cout << "sum of items: " << sum << "\n";
    std::cout << "each item consumed once: " << (consumed == expected ? "True" : "False") << "\n";
}
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: idiom. BoundedBuffer is a small class: a std::deque with a mutex and the two condition variables not_full_ and not_empty_.
JavaGitHub
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class Main {
    static final Integer DONE = -1; // the end-of-stream object

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> buffer = new ArrayBlockingQueue<>(4);
        List<Integer> consumed = Collections.synchronizedList(new ArrayList<>());
        List<Thread> producers = new ArrayList<>();
        List<Thread> consumers = new ArrayList<>();
        for (int s : new int[] {0, 500}) {
            producers.add(new Thread(() -> {
                try {
                    for (int item = s; item < s + 500; item++) buffer.put(item);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }));
        }
        for (int i = 0; i < 2; i++) {
            consumers.add(new Thread(() -> {
                try {
                    while (true) {
                        Integer item = buffer.take();
                        if (item.equals(DONE)) return;
                        consumed.add(item);
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }));
        }
        for (Thread t : producers) t.start();
        for (Thread t : consumers) t.start();
        for (Thread t : producers) t.join();
        for (Thread t : consumers) buffer.put(DONE); // one for each consumer
        for (Thread t : consumers) t.join();

        List<Integer> sorted = new ArrayList<>(consumed);
        Collections.sort(sorted);
        boolean once = sorted.size() == 1000;
        for (int i = 0; once && i < 1000; i++) once = sorted.get(i) == i;
        long sum = 0;
        for (int x : sorted) sum += x;
        System.out.println("items consumed: " + consumed.size());
        System.out.println("sum of items: " + sum);
        System.out.println("each item consumed once: " + (once ? "True" : "False"));
    }
}
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: stdlib. ArrayBlockingQueue with capacity 4 is the bounded buffer: put waits when it is full and take waits when it is empty.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Program
{
    static void Main()
    {
        var buffer = new BlockingCollection<int>(boundedCapacity: 4);
        var consumed = new ConcurrentBag<int>();
        var producers = new[] { 0, 500 }.Select(s => new Thread(() =>
        {
            for (int item = s; item < s + 500; item++) buffer.Add(item);
        })).ToList();
        var consumers = Enumerable.Range(0, 2).Select(_ => new Thread(() =>
        {
            foreach (var item in buffer.GetConsumingEnumerable()) consumed.Add(item);
        })).ToList();
        foreach (var t in producers.Concat(consumers)) t.Start();
        foreach (var t in producers) t.Join();
        buffer.CompleteAdding(); // the end of the stream for every consumer
        foreach (var t in consumers) t.Join();

        var sorted = consumed.OrderBy(x => x).ToList();
        Console.WriteLine("items consumed: " + sorted.Count);
        Console.WriteLine("sum of items: " + sorted.Sum(x => (long)x));
        Console.WriteLine("each item consumed once: " + sorted.SequenceEqual(Enumerable.Range(0, 1000)));
    }
}
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: stdlib. BlockingCollection with boundedCapacity: 4 is the bounded buffer, and CompleteAdding ends the stream instead of an end-of-stream object.
JavaScriptGitHub
class BoundedBuffer {
  constructor(capacity) {
    this.capacity = capacity;
    this.items = [];
    this.waitingPutters = []; // resolvers of producers that wait for space
    this.waitingTakers = []; // resolvers of consumers that wait for an item
    this.closed = false;
  }

  async put(item) {
    while (this.items.length >= this.capacity) {
      await new Promise((resolve) => this.waitingPutters.push(resolve));
    }
    this.items.push(item);
    this.waitingTakers.shift()?.();
  }

  async take() {
    while (this.items.length === 0) {
      if (this.closed) return undefined; // the stream has ended
      await new Promise((resolve) => this.waitingTakers.push(resolve));
    }
    const item = this.items.shift();
    this.waitingPutters.shift()?.();
    return item;
  }

  close() {
    this.closed = true;
    for (const wake of this.waitingTakers.splice(0)) wake();
  }
}

async function main() {
  const buffer = new BoundedBuffer(4);
  const consumed = [];

  async function producer(start) {
    for (let item = start; item < start + 500; item++) await buffer.put(item);
  }

  async function consumer() {
    for (;;) {
      const item = await buffer.take();
      if (item === undefined) return;
      consumed.push(item);
    }
  }

  const consumers = [consumer(), consumer()];
  await Promise.all([producer(0), producer(500)]);
  buffer.close(); // the end of the stream for every consumer
  await Promise.all(consumers);

  consumed.sort((a, b) => a - b);
  const once = consumed.length === 1000 && consumed.every((x, i) => x === i);
  console.log("items consumed:", consumed.length);
  console.log("sum of items:", consumed.reduce((a, b) => a + b, 0));
  console.log("each item consumed once:", once ? "True" : "False");
}

main();
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: idiom. The producers and consumers are async functions on one event loop, and BoundedBuffer keeps the resolvers of the ones that wait for space or for an item.
TypeScriptGitHub
class BoundedBuffer {
  capacity: number;
  items: number[] = [];
  waitingPutters: (() => void)[] = []; // resolvers of producers that wait for space
  waitingTakers: (() => void)[] = []; // resolvers of consumers that wait for an item
  closed = false;

  constructor(capacity: number) {
    this.capacity = capacity;
  }

  async put(item: number): Promise<void> {
    while (this.items.length >= this.capacity) {
      await new Promise<void>((resolve) => this.waitingPutters.push(resolve));
    }
    this.items.push(item);
    this.waitingTakers.shift()?.();
  }

  async take(): Promise<number | undefined> {
    while (this.items.length === 0) {
      if (this.closed) return undefined; // the stream has ended
      await new Promise<void>((resolve) => this.waitingTakers.push(resolve));
    }
    const item = this.items.shift();
    this.waitingPutters.shift()?.();
    return item;
  }

  close(): void {
    this.closed = true;
    for (const wake of this.waitingTakers.splice(0)) wake();
  }
}

async function main(): Promise<void> {
  const buffer = new BoundedBuffer(4);
  const consumed: number[] = [];

  async function producer(start: number): Promise<void> {
    for (let item = start; item < start + 500; item++) await buffer.put(item);
  }

  async function consumer(): Promise<void> {
    for (;;) {
      const item = await buffer.take();
      if (item === undefined) return;
      consumed.push(item);
    }
  }

  const consumers = [consumer(), consumer()];
  await Promise.all([producer(0), producer(500)]);
  buffer.close(); // the end of the stream for every consumer
  await Promise.all(consumers);

  consumed.sort((a, b) => a - b);
  const once = consumed.length === 1000 && consumed.every((x, i) => x === i);
  console.log("items consumed:", consumed.length);
  console.log("sum of items:", consumed.reduce((a, b) => a + b, 0));
  console.log("each item consumed once:", once ? "True" : "False");
}

main();
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: idiom. The producers and consumers are async functions on one event loop, and BoundedBuffer keeps the resolvers of the ones that wait for space or for an item.
package main

import (
	"fmt"
	"sort"
	"sync"
)

func main() {
	buffer := make(chan int, 4) // a send waits when 4 items wait
	var mu sync.Mutex
	var consumed []int

	var producers sync.WaitGroup
	for _, start := range []int{0, 500} {
		producers.Add(1)
		go func(start int) {
			defer producers.Done()
			for item := start; item < start+500; item++ {
				buffer <- item
			}
		}(start)
	}
	var consumers sync.WaitGroup
	for i := 0; i < 2; i++ {
		consumers.Add(1)
		go func() {
			defer consumers.Done()
			for item := range buffer { // the loop ends when the channel is closed and empty
				mu.Lock()
				consumed = append(consumed, item)
				mu.Unlock()
			}
		}()
	}
	producers.Wait()
	close(buffer) // the end of the stream for every consumer
	consumers.Wait()

	sort.Ints(consumed)
	sum, once := 0, len(consumed) == 1000
	for i, x := range consumed {
		sum += x
		once = once && x == i
	}
	fmt.Println("items consumed:", len(consumed))
	fmt.Println("sum of items:", sum)
	if once {
		fmt.Println("each item consumed once: True")
	} else {
		fmt.Println("each item consumed once: False")
	}
}
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: native. A channel with a buffer of 4 is the bounded buffer, and close ends the range loop of each consumer.
RustGitHub
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let (sender, receiver) = mpsc::sync_channel::<u64>(4); // send waits when 4 items wait
    let receiver = Arc::new(Mutex::new(receiver));
    let consumed = Arc::new(Mutex::new(Vec::new()));

    let producers: Vec<_> = [0u64, 500]
        .into_iter()
        .map(|start| {
            let sender = sender.clone();
            thread::spawn(move || {
                for item in start..start + 500 {
                    sender.send(item).unwrap();
                }
            })
        })
        .collect();
    drop(sender); // the stream ends when every sender is dropped

    let consumers: Vec<_> = (0..2)
        .map(|_| {
            let receiver = Arc::clone(&receiver);
            let consumed = Arc::clone(&consumed);
            thread::spawn(move || loop {
                let message = receiver.lock().unwrap().recv();
                match message {
                    Ok(item) => consumed.lock().unwrap().push(item),
                    Err(_) => break,
                }
            })
        })
        .collect();
    for t in producers.into_iter().chain(consumers) {
        t.join().unwrap();
    }

    let mut items = consumed.lock().unwrap().clone();
    items.sort();
    let once = items == (0..1000).collect::<Vec<u64>>();
    println!("items consumed: {}", items.len());
    println!("sum of items: {}", items.iter().sum::<u64>());
    println!("each item consumed once: {}", if once { "True" } else { "False" });
}
Output
items consumed: 1000
sum of items: 499500
each item consumed once: True
  • Verdict: stdlib. mpsc::sync_channel(4) is the bounded buffer. The receiver has one owner, so the consumers share it behind Arc<Mutex<_>>.

Consequences

Benefits:

  • The producer and the consumer do not call each other. They share only the buffer.
  • A bounded buffer stops a fast producer. The insertion blocks once the size has been reached, until queue items are consumed.4
  • A BlockingQueue can safely be used with multiple producers and multiple consumers.3

Liabilities:

  • The buffer needs a way to end. A BlockingQueue does not intrinsically support any kind of "close" or "shutdown" operation. A common tactic is for producers to insert special end-of-stream or poison objects.3
  • The size of the buffer is a test of the moment only. If empty() returns True, the Python documentation does not guarantee that a subsequent call to put() will not block, and a False result does not guarantee that get() will not block.4

A consumer that stops when the buffer is empty misses the items of a slow producer:

This code runs but gives a wrong answer on purpose.

import queue
import threading

buffer = queue.Queue()
consumed = []
consumer_checked = threading.Event()


def consumer():
    while not buffer.empty():  # wrong: an empty buffer is not the end
        consumed.append(buffer.get())
    consumer_checked.set()


def producer():
    consumer_checked.wait()  # the producer is slow to start
    for item in range(10):
        buffer.put(item)


threads = [threading.Thread(target=consumer), threading.Thread(target=producer)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("items produced:", 10)
print("items consumed:", len(consumed))
Output
items produced: 10
items consumed: 0

When not to use it

If the consumer must answer the producer, such as a request that waits for its result, a one-way buffer is not enough. Use a future or a reply channel for each item instead. If the producer and the consumer run in one thread, call the consumer directly. A buffer between them adds work and no concurrency.

  • Semaphores. Dijkstra's original solution uses the two counting semaphores and a mutex.2 The example follows it:
import threading
from collections import deque

N = 4
queuing_portions = threading.Semaphore(0)  # counts the filled places
empty_positions = threading.Semaphore(N)  # counts the empty places
buffer_manipulation = threading.Lock()  # the mutex for the buffer
buffer = deque()
consumed = []


def producer():
    for portion in range(1000):
        empty_positions.acquire()  # P(number of empty positions)
        with buffer_manipulation:
            buffer.append(portion)
        queuing_portions.release()  # V(number of queuing portions)


def consumer():
    for _ in range(1000):
        queuing_portions.acquire()  # P(number of queuing portions)
        with buffer_manipulation:
            portion = buffer.popleft()
        empty_positions.release()  # V(number of empty positions)
        consumed.append(portion)


threads = [threading.Thread(target=producer), threading.Thread(target=consumer)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("portions consumed:", len(consumed))
print("in order:", consumed == list(range(1000)))
Output
portions consumed: 1000
in order: True
  • Monitor. A bounded buffer monitor contains the buffer, the count and the condition variables nonempty and nonfull, and the methods append and remove.1 Monitor Object states this form as a pattern.
  • Channels. A Go channel with a buffer is a bounded buffer. If the buffer is full, the sender waits until some receiver has retrieved a value.5 If the channel is unbuffered, the sender blocks until the receiver has received the value.5
  • Shutdown. The Python Queue.shutdown method puts a queue into a shutdown mode. Future calls to put() raise ShutDown, and once the queue is empty, future calls to get() raise ShutDown.4

A Thread pool is a producer-consumer arrangement in which the consumers are the workers and the items are tasks. Half-Sync/Half-Async puts a queue of this kind between its two layers.

Known uses

  • Java: ArrayBlockingQueue, LinkedBlockingQueue and the other BlockingQueue implementations.3
  • Python: queue.Queue, queue.LifoQueue and queue.PriorityQueue, where maxsize sets the upper bound of items.4
  • Go: channels with a buffer.5
  • Dijkstra gives the Electrologica X1 and X8 computers as the first use: two counting semaphores controlled the transport of information between store and peripheral.1

References

  1. Producer-consumer problem, Wikipedia, lead; Dijkstra's bounded buffer solution; Using monitors; Using channels
  2. Edsger W. Dijkstra, Cooperating sequential processes (EWD123), 4.1 Typical Uses of the General Semaphore; 4.3 The Bounded Buffer
  3. BlockingQueue, Java SE 21 API documentation, interface description
  4. queue, A synchronized queue class, Python documentation, class queue.Queue; Queue Objects
  5. Effective Go, Channels

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/RXGQZP/text.yaml