Use queue.Queue (thread-safe by design, unlike a plain list) — producer thread(s) call .put() to add work items, and multiple consumer/worker threads call .get() in a loop to pull and process items, with the queue's internal locking handling all synchronization automatically without you writing manual locks.
import threading, queue
q = queue.Queue()
def worker():
while True:
item = q.get()
if item is None:
break
print(f"Processing {item}")
q.task_done()
threads = [threading.Thread(target=worker) for _ in range(3)]
for t in threads: t.start()
for i in range(10): q.put(i)
for _ in threads: q.put(None) # sentinel to stop each worker
for t in threads: t.join()
Real-world example
Building a multi-threaded task processing system where several worker threads pull jobs from a shared, thread-safe queue.
Likely follow-ups
How does queue.Queue's internal locking differ from what you'd need to write manually with threading.Lock alone?
Call task.cancel() to request cancellation, which raises asyncio.CancelledError inside the task at its next 'await' suspension point — the task SHOULD let this exception propagate (after any necessary cleanup in a finally block) rather than silently catching and suppressing it, since swallowing CancelledError breaks the task's ability to actually be cancelled.
async def long_running():
try:
await asyncio.sleep(100)
except asyncio.CancelledError:
print("Cleaning up before cancellation")
raise # MUST re-raise to properly complete cancellation
async def main():
task = asyncio.create_task(long_running())
await asyncio.sleep(1)
task.cancel()
await asyncio.gather(task, return_exceptions=True)
Real-world example
Cancelling a long-running background task (like a polling loop) cleanly when a user navigates away or a shutdown signal is received.
Likely follow-ups
What happens if a cancelled task's except block swallows CancelledError instead of re-raising it?
Combine loop.run_in_executor() with a ProcessPoolExecutor instance (instead of the default thread pool) to offload genuinely CPU-bound work to a separate PROCESS, bypassing the GIL for true parallelism, while still awaiting the result asynchronously from within your asyncio application.
import asyncio
from concurrent.futures import ProcessPoolExecutor
def cpu_heavy(n):
return sum(i * i for i in range(n))
async def main():
loop = asyncio.get_running_loop()
with ProcessPoolExecutor() as pool:
result = await loop.run_in_executor(pool, cpu_heavy, 10_000_000)
print(result)
Real-world example
Running a CPU-intensive computation (like image processing or numerical analysis) from within an async web server without blocking request handling.
Likely follow-ups
Why must arguments passed to a ProcessPoolExecutor's function be picklable, unlike with a ThreadPoolExecutor?
Use an asyncio.Event or a shutdown flag checked cooperatively by workers for GRACEFUL shutdown (letting in-flight tasks complete before stopping), versus explicitly calling task.cancel() on all worker tasks for IMMEDIATE cancellation — combining both gives you a controllable shutdown sequence, often triggered by an OS signal handler.
async def worker(queue, shutdown_event):
while not shutdown_event.is_set():
try:
item = await asyncio.wait_for(queue.get(), timeout=0.5)
await process(item)
except asyncio.TimeoutError:
continue # check shutdown_event again
async def graceful_shutdown(shutdown_event):
shutdown_event.set() # workers finish current item, then stop cleanly
Real-world example
Building a production task-processing service that shuts down gracefully on SIGTERM, finishing in-flight work rather than dropping it.
Likely follow-ups
How would you register an OS signal handler (like SIGTERM) to trigger this graceful shutdown sequence in an asyncio application?
A race condition occurs when the outcome of concurrent operations depends on unpredictable timing, typically causing lost updates or corrupted shared state; a deadlock occurs when two or more threads/processes each hold a resource the other needs and wait forever, making no progress at all. Race conditions produce wrong results silently; deadlocks freeze the program entirely.
# Race condition: lost updates without a lock
counter = 0
def increment():
global counter
counter += 1 # not atomic: read, add, write can interleave between threads
# Deadlock: each thread waits on a lock the other holds
# Thread A: lock1.acquire(); lock2.acquire()
# Thread B: lock2.acquire(); lock1.acquire() -- opposite order, can deadlock
Real-world example
Debugging a counter that mysteriously undercounts under load (race condition) versus a service that hangs indefinitely under specific load patterns (deadlock).
Likely follow-ups
What is the standard technique (like consistent lock ordering) for avoiding deadlocks in multi-lock code?