← All Exercises
Producer-Consumer with a Bounded Queue
advancedpython
Background
A bounded queue applies backpressure and decouples production from consumption; sentinels are a simple shutdown protocol when the number of workers is fixed.
Problem
Implement process(numbers, capacity, consumers) that sends each integer through a bounded queue to consumer threads, squares it, and returns all squares sorted. Use one sentinel per consumer so every worker exits, and validate capacity and consumers are positive.
Input
A list of integers, a positive queue capacity, and a positive consumer count.
Output
A sorted list with one square per input value.
Sample tests
Sample 1
Input: numbers = [1, 2, 3, 4], capacity = 2, consumers = 2
Expected: [1, 4, 9, 16]
Sample 2
Input: numbers = [], capacity = 1, consumers = 3
Expected: []
Your solution
Learning objective
Build a deadlock-free bounded producer-consumer pipeline with deterministic shutdown.