`Queue`
queue.Queue is a thread-safe FIFO used to pass work between producer and consumer threads. multiprocessing.Queue does the same across processes. asyncio.Queue does it among tasks.
Detailed Explanation
Shared memory plus locks is one way to talk between threads. A queue is the other: producers put items, consumers get them, and the queue owns the lock and the waiting. You do not touch the same list from two threads.
queue.Queue(maxsize=0) is unbounded when maxsize is 0. A positive maxsize makes put block when the queue is full — backpressure. get blocks when it is empty. put_nowait and get_nowait raise queue.Full and queue.Empty. task_done and join let a producer wait until every enqueued item has been processed. Forgetting task_done makes join hang.
LifoQueue is a stack. PriorityQueue is a heap of (priority, item) tuples. Items must be comparable, so put a tie-breaker in the tuple.
multiprocessing.Queue pickles items into a pipe. The child process must be started with a __main__ guard. A process queue that is not closed or joined can prevent a child from exiting. Call cancel_join_thread only when you understand you will drop leftover items.
asyncio.Queue is not thread-safe. Use it between coroutines on one loop. For a thread talking to asyncio, use loop.call_soon_threadsafe or janus/an explicit bridge, not asyncio.Queue.put from the thread.
Do not use queue.Queue.get inside a coroutine: it blocks the event loop. Do not use asyncio.Queue from two threads.
Sentinel values (None, a dedicated STOP object) are the usual way to tell consumers to exit. Put one sentinel per consumer.
Code Examples
from queue import Queue
from threading import Thread
def worker(pending: Queue) -> None:
while True:
item = pending.get()
if item is None:
pending.task_done()
break
pending.task_done()
pending: Queue[str | None] = Queue()
t = Thread(target=worker, args=(pending,))
t.start()
pending.put("resize")
pending.put(None) # one worker, one sentinel
pending.join()
t.join()import asyncio
async def pump() -> None:
q: asyncio.Queue[int] = asyncio.Queue(maxsize=2)
await q.put(1)
print(await q.get()) # 1Common Gotchas
`join` without `task_done`
hangs forever.
Blocking `Queue.get` in asyncio
freezes the loop. Use `asyncio.Queue`.
One sentinel per consumer
three workers need three `None`s, or a shared `Event` plus empty-queue checks.
`PriorityQueue` compares the whole tuple
incomparable items at equal priority raise `TypeError`.