One-Line Definition
A queue processes elements in First-In, First-Out (FIFO) order, while a double-ended queue (deque) supports insertion and removal at both ends; thread, coroutine, and inter-process queues layer waiting and synchronization semantics on top.
Why It Matters
- Drives Breadth-First Search (BFS) (see k2.algo.bfs).
- Task scheduling and load smoothing: Buffering incoming requests, decoupling producer and consumer workers across threads or coroutines, and enforcing backpressure.
- Sliding windows: Keeping only the most recent items in bounded memory.
Usage Boundaries
queue.Queue synchronizes OS threads, whereas asyncio.Queue coordinates coroutines inside an event loop. Even when single container operations are atomic, multi-step patterns like "check if non-empty, then pop" are not atomic across concurrent consumers; and while bounded queues enforce backpressure on producers, they do not by themselves enforce external API rate limits.
How It Works / Diagram
| Python Construct | Best Suited For |
|---|---|
collections.deque |
Single-threaded FIFO/LIFO, at both ends, supports bounded maxlen sliding windows |
queue.Queue |
Multi-threaded producer-consumer pipelines with blocking put / get |
asyncio.Queue |
Async coroutines on a single event loop (not thread-safe) |
heapq / queue.PriorityQueue |
Dequeuing by priority order rather than arrival order (see k2.ds.heap) |
See the Python queue module docs: https://docs.python.org/3/library/queue.html and asyncio.Queue docs: https://docs.python.org/3/library/asyncio-queue.html
Runnable Example
Basic deque FIFO operations, a bounded maxlen sliding window, a multi-threaded producer-consumer queue with backpressure, and an asyncio.Queue (verified on Python 3.15.0):
# File: examples/11_queue.py
# Queue: First-In, First-Out (FIFO). Always use collections.deque rather than list.pop(0)
from collections import deque
q = deque()
for job in ["TaskA", "TaskB", "TaskC"]: q.append(job)
print("Dequeue order:", [q.popleft() for _ in range(len(q))])
# Fixed-length sliding window (e.g., last N chat turns or moving loss average)
window = deque(maxlen=3)
for loss in [2.0, 1.5, 1.2, 1.0, 0.9]:
window.append(loss)
print(f"New value {loss} -> window {list(window)} avg {sum(window)/len(window):.2f}")
# Thread-safe bounded queue: producer-consumer pattern
import queue, threading
jobs, results = queue.Queue(maxsize=2), []
def worker():
while (item := jobs.get()) is not None:
results.append(item * item); jobs.task_done()
jobs.task_done()
t = threading.Thread(target=worker); t.start()
for i in range(5): jobs.put(i) # Blocks when maxsize=2 is full (backpressure)
jobs.put(None); jobs.join(); t.join()
print("Consumer results:", results)
# Priority queues (see 'Heaps') and asyncio.Queue belong to the same queue family
import asyncio
async def main():
aq = asyncio.Queue()
for i in range(3): await aq.put(f"Req{i}")
return [await aq.get() for _ in range(3)]
print("asyncio.Queue:", asyncio.run(main()))
Recorded output:
Dequeue order: ['TaskA', 'TaskB', 'TaskC']
New value 2.0 -> window [2.0] avg 2.00
New value 1.5 -> window [2.0, 1.5] avg 1.75
New value 1.2 -> window [2.0, 1.5, 1.2] avg 1.57
New value 1.0 -> window [1.5, 1.2, 1.0] avg 1.23
New value 0.9 -> window [1.2, 1.0, 0.9] avg 1.03
Consumer results: [0, 1, 4, 9, 16]
asyncio.Queue: ['Req0', 'Req1', 'Req2']
Common Misconceptions
- Using
list.pop(0)as a queue: Removing index 0 from a contiguous array shifts every remaining element left in time; always usecollections.deque.popleft()for dequeuing. - Using
dequeacross threads with check-then-act logic: While individualappendandpopleftcalls are atomic in CPython, checkingif dq:before callingdq.popleft()is a race condition across threads—usequeue.Queueinstead. - Calling blocking
queue.Queue.get()inside anasync defcoroutine: Doing so blocks the entire event loop thread; useawait asyncio.Queue.get()instead (see k1.py.async-await). - Leaving production queues unbounded: When producers outpace consumers, an unbounded queue grows until the process runs out of memory; set
maxsizeto apply backpressure.
Connection to AI Development
- Concurrency limiting for LLM API requests: Feeding tasks into a bounded queue consumed by a fixed pool of workers keeps in-flight concurrency within your provider's rate limits cleanly.
- Continuous batching in inference servers: Serving engines like vLLM maintain waiting and running request queues to schedule token generation batches dynamically: https://docs.vllm.ai/en/latest/design/arch_overview.html
- Rolling chat memory window:
deque(maxlen=N)retains the latest conversation turns while automatically evicting older messages.
Further Reading
- Python
collections.deque: https://docs.python.org/3/library/collections.html#collections.deque - Python
queueModule: https://docs.python.org/3/library/queue.html - Python
asyncio.Queue: https://docs.python.org/3/library/asyncio-queue.html
Comprehension Check
Why can multiple consumer threads still crash with an empty-queue error if each thread checks if not q.empty(): right before calling q.get_nowait()?
Reference answer: Between the moment Thread A checks not q.empty() and the moment it calls get_nowait(), Thread B can pop the final item—classic Time-of-Check to Time-of-Use (TOCTOU). Consumers should use blocking q.get() (with sentinel values or timeouts) instead of check-then-act polling.
Verification & Reproduction
Verified on: 2026-10-14. Example status: Passed. Run log: 11_queue.py.
Companion Code & Verification Materials