Queue Hands Tasks Across Threads Safely
queue.Queue moves tasks between threads without manual locks; task_done and join form a completion barrier, and a sentinel stops the worker.
Code
import queue
import threading
tasks = queue.Queue()
results = []
def worker():
# iter(callable, sentinel):get 到 None 哨兵时结束循环,不必手写退出条件
for item in iter(tasks.get, None):
results.append(item.upper())
tasks.task_done() # 每个取出的项都必须标记完成,join 的栅栏才能打开
# 生产者:主线程把任务放进共享队列
for name in ["billing", "auth", "inventory", "search"]:
tasks.put(name)
# 消费者:后台线程与主线程通过队列交接,不用手动加锁
thread = threading.Thread(target=worker, name="worker-1")
thread.start()
tasks.join() # 阻塞到所有取出的任务都 task_done
tasks.put(None) # 哨兵让 worker 正常退出
thread.join()
print("results:", results)
print("queue empty:", tasks.empty())Output
Captured from a sandboxed run of this snippet in the build pipeline.
results: ['BILLING', 'AUTH', 'INVENTORY', 'SEARCH']
queue empty: TrueHow it works
The working surface is the function worker — everything else is wiring.
One loop does the cycling here: for item in iter(tasks.get, None).
Caveats
- Dependency check:
queueandthreading— not built-in, must be present in the project.
Applying it
Entry signature: def worker()
The demo output is labeled (results:, queue empty:), so every printed line maps back to its originating operation.
worker is what another module would consume; nothing else here is load-bearing for callers.
Statements that matter
for item in iter(tasks.get, None):
results.append(item.upper())
tasks.task_done() # 每个取出的项都必须标记完成,join 的栅栏才能打开
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Every import resolves inside the standard library — `queue`, `threading`. The file defines `worker` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.