liveBook · Manning

Bounded queue

As explained in Software Design for Python Programmers

A queue with a fixed maximum capacity that can become full when it contains that many values.

A bounded queue stores values in order while enforcing a fixed maximum capacity. Producers add values at the tail; consumers remove them from the head. When full, producers wait; when empty, consumers wait. section 16.4 section 16.4.2

In a concurrent producer–consumer design, the queue coordinates these state transitions:

  • Acquire a shared condition object before checking whether the queue is full or empty. section 16.4.1
  • Wait in a loop when the queue remains full for a producer or empty for a consumer. section 16.4.1
  • Notify waiting threads after an insertion makes the queue nonempty or a removal makes it nonfull. section 16.4
  • Recheck the condition after waking because another thread may have changed the queue first. section 16.4.1

Two producers and three consumers

A Python example constructs BoundedQueue(8), runs two producers for five turns each, and runs three consumers. Producers enter values, consumers remove them, and a zero sentinel lets consumers terminate after production finishes. section 16.4.2

Figure 16.9 The producer and consumer threads each attempt to acquire queue.condition at the top of its loop. The condition object synchronizes the producer and consumer threads. The producer threads loop to enter values into the shared bounded queue, and the consumer threads loop to remove values from the queue. A producer thread cannot enter a value into the queue when the queue is full. A consumer thread cannot remove a value from an empty queue.
A diagram of a process

AI-generated content may be incorrect.

Use the synchronization diagram to trace how producers and consumers acquire the condition, wait, modify the queue, and notify one another. section 16.4.1

How Software Design for Python Programmers covers it

How deep it goes
Defines queue operations and condition-based synchronization, including waiting, reacquisition, rechecking, and notification.
Examples
Uses Python classes, two producers, three consumers, capacity eight, queue-state output, and zero end sentinels.
What it assumes
Assumes basic queues and threads while developing condition-based coordination beyond mutexes and semaphores alone.
What you can do after
Build it from scratch using Python threading conditions to synchronize bounded producer-consumer workflows.
How it connects
Connects producer-consumer problems with threads, condition objects, mutexes, semaphores, and shared resources.

Also explained in

Compare how 3 books explain bounded queue →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.