Part 13 / Topic 10 of 11
Common pitfalls
Blocking the event loop
time.sleep (or urllib, or a long loop) inside async def freezes every task, because there is only one thread.
import asyncio
import time
async def bad() -> None:
time.sleep(0.2) # ❌ blocks everyone
async def good() -> None:
await asyncio.sleep(0.2) # ✅ only this task waits
async def main() -> None:
start = time.perf_counter()
await asyncio.gather(bad(), bad())
print(f"bad: {time.perf_counter() - start:.1f} s") # bad: 0.4 s (time varies)
start = time.perf_counter()
await asyncio.gather(good(), good())
print(f"good: {time.perf_counter() - start:.1f} s") # good: 0.2 s (time varies)
asyncio.run(main())
Forgetting await
Without await, a coroutine never runs. Python only warns you (RuntimeWarning: coroutine '...' was never awaited), and you get a coroutine object instead of a result.
import asyncio
async def get_total() -> int:
return 1760
async def main() -> None:
total = get_total() # ❌ forgot await
print(type(total).__name__) # coroutine
total.close() # (only to silence the warning in this demo)
print(await get_total()) # 1760 ✅
asyncio.run(main())
Deadlocks
A deadlock is when threads wait for each other forever, and nothing moves. A common one: thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Even one thread can deadlock itself by taking the same Lock twice:
import threading
lock = threading.Lock()
with lock:
# A plain Lock cannot be taken twice. Without the timeout this waits forever.
got_it = lock.acquire(timeout=0.1)
print("got the lock again?", got_it) # got the lock again? False
Fixes: take locks in the same order everywhere, keep locked sections small, prefer queue.Queue over many locks, and use timeouts.
Too many threads
Each thread uses memory and the operating system must keep switching between them. 10,000 threads make a program slower, not faster, and hammer the server. Use a pool with a sensible size (ThreadPoolExecutor(max_workers=10)) or a Semaphore.
Done here? The practice set for Part 13 — 8 exercises with solutions — is on the part page.