On this page
  1. queue
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Producer / Consumer Worker Pattern with Sentinel Shutdown
  7. Gotchas & Boundaries
  8. Classes & Objects

queue

Prev: pyexpat | Up: stdlib_module | Next: quopri
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — queue
Tags: #public #python3 #stdlib


Import

import queue

Overview

Thread-safe, synchronized FIFO (Queue), LIFO (LifoQueue), priority (PriorityQueue), and lightweight unbounded (SimpleQueue) queues for coordinating producer and consumer threads. Always prefer queue.Queue over sharing a plain list with a manual lock across threading workers.

Quick Start

import queue

q: queue.Queue[str] = queue.Queue(maxsize=2)
q.put("job-1")
q.put("job-2")
assert q.get() == "job-1"
q.task_done()
assert q.get() == "job-2"
q.task_done()
q.join()

Implementation Walkthrough

1. Producer / Consumer Worker Pattern with Sentinel Shutdown

Use a dedicated sentinel object (None or object()) and maxsize backpressure so producers cannot outrun consumers and exhaust memory:

import queue
import threading

STOP = object()
q: queue.Queue[object] = queue.Queue(maxsize=4)
results: list[int] = []

def worker() -> None:
    while True:
        item = q.get()
        try:
            if item is STOP:
                return
            assert isinstance(item, int)
            results.append(item * 10)
        finally:
            q.task_done()

t = threading.Thread(target=worker)
t.start()
for n in (1, 2, 3):
    q.put(n)
q.put(STOP)
q.join()
t.join()
assert results == [10, 20, 30]

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes