Sub topic 11
Limiting and coordinating tasks
This chapter assumes you can write coroutines, start tasks with asyncio.create_task, and collect results with asyncio.gather. It covers the synchronization primitives that limit how many tasks run at once and let tasks wait for each other.
Why tasks need coordination
Tasks share one thread, so they never run at the same instant. They can still interfere with each other. A task can be suspended at any await, and another task can then change shared state. Unbounded concurrency causes a second problem. If you start 10,000 requests at once, you can exhaust file descriptors or overload the server you call.
asyncio provides three primitives for these problems:
| Primitive | Purpose |
|---|---|
| `Semaphore` | Allow at most N tasks inside a block |
| `Lock` | Allow only one task inside a block |
| `Event` | Let tasks wait until a signal is set |
Capping concurrency with Semaphore
A Semaphore(n) holds a counter that starts at n. Entering async with sem takes one slot. If none are free, the task waits. Leaving the block returns the slot.
import asyncio
async def worker(sem, n):
async with sem:
await asyncio.sleep(0.1)
return n
async def main():
sem = asyncio.Semaphore(2)
results = await asyncio.gather(*(worker(sem, n) for n in range(6)))
print(results)
asyncio.run(main())All six workers start, but only two are inside the guarded block at any moment. The program prints [0, 1, 2, 3, 4, 5] after about 0.3 seconds. gather returns results in input order, whatever order the workers finish in.
Protecting shared state with Lock
A Lock is a semaphore with one slot. You need it only when a critical section contains an await. Code between two awaits can't be interrupted, so a plain increment is already safe.
import asyncio
balance = 100
lock = asyncio.Lock()
async def withdraw(amount):
global balance
async with lock:
current = balance
await asyncio.sleep(0.01) # a task switch can happen here
balance = current - amount
async def main():
await asyncio.gather(withdraw(10), withdraw(20), withdraw(30))
print(balance)
asyncio.run(main())This prints 40. Remove the lock and all three tasks read 100, so the final balance is wrong.
Signalling with Event
An Event holds a flag. Tasks call await event.wait() and pause until another task calls event.set(). Once the flag is set, every current and future wait() returns immediately.
import asyncio
async def waiter(name, ready):
await ready.wait()
print(name, "started")
async def main():
ready = asyncio.Event()
tasks = [asyncio.create_task(waiter(f"task-{i}", ready)) for i in range(3)]
await asyncio.sleep(0.1)
print("setting event")
ready.set()
await asyncio.gather(*tasks)
asyncio.run(main())Common mistakes
- Creating the semaphore outside the running loop on older Python versions. Create it inside a coroutine, or in
main, to be safe. - Holding a
Lockacross a longawait, such as a network call. Other tasks queue up behind it. - Using
Lockfor a section with noawait. It adds cost and protects nothing. - Calling
event.set()and expecting waiters to run immediately. They run only when the setter next yields to the loop.
Exercise
You start 100 tasks that each call a web API, and the server allows only 5 simultaneous requests. Which primitive do you use, and where do you put it?
Show answer
Create asyncio.Semaphore(5) and wrap only the API call in async with sem: inside each task. All 100 tasks start, but at most 5 are inside the call at once.
Exercise
Why is a Lock unnecessary around counter += 1 in a coroutine when there is no await in the block?
Show answer
Tasks switch only at an await. With no await between the read and the write, no other task can run in between, so the update can't be interleaved.