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 also assumes you know what a context manager is. Here you will use Lock, Event, and Semaphore to control how tasks share resources, signal each other, and cap how many run at once.
Why one thread still needs coordination
All tasks in an event loop run on one thread. A task only gives up control at an await. Code between two awaits cannot be interrupted by another task.
That removes many races, but not all of them. Any time shared state is read, then an await happens, then the state is written, another task can run in the gap. The read is now stale. Coordination primitives exist for this case, and for two others: making one task wait for a signal, and limiting how many tasks use a resource at once.
| Primitive | Question it answers | Typical use |
|---|---|---|
| `Lock` | Who may touch this state right now? | Read-modify-write across an `await` |
| `Event` | Has the thing I'm waiting for happened? | Start signals, shutdown flags |
| `Semaphore` | How many of us may be inside at once? | Capping requests to a server |
All three live in asyncio, work only with await and async with, and are not thread-safe. Use them from coroutines on one event loop, not from other threads.
Lock: one task at a time
An asyncio.Lock lets one task hold it at a time. Other tasks that call acquire suspend until the holder releases. Use it with async with so it is released even if an exception occurs.
The program below withdraws 10 five times from a balance of 100. Each withdrawal reads the balance, awaits (simulating a database call), then writes the new value.
import asyncio
balance = 100
async def withdraw(lock, amount):
global balance
async with lock:
current = balance
await asyncio.sleep(0.01)
balance = current - amount
async def main():
lock = asyncio.Lock()
await asyncio.gather(*(withdraw(lock, 10) for _ in range(5)))
print(balance)
asyncio.run(main())This prints 50. Replace async with lock: with a plain block, and every task reads 100 before any of them writes, so the program prints 90. The lost updates came from the await inside the read-modify-write, not from threads.
Things to know about Lock:
- It is not reentrant. A task that already holds the lock and tries to acquire it again waits forever, because it is waiting for itself.
- Keep the guarded block short. Every other task that needs the lock waits while you hold it, so avoid long awaits inside it.
- If the read and write have no
awaitbetween them, you do not need a lock. Code between awaits already runs without interruption. lock.locked()reports the state, but checking it and then acquiring is not a safe pattern. Just acquire.
Event: a flag tasks can wait on
An asyncio.Event holds a boolean flag, initially false. Tasks call await event.wait() to suspend until the flag is true. Calling event.set() sets it and wakes every waiter. Calling event.clear() resets it, and event.is_set() reads it.
import asyncio
async def waiter(name, ready):
print(name, "waiting")
await ready.wait()
print(name, "started")
async def main():
ready = asyncio.Event()
tasks = [asyncio.create_task(waiter(f"w{i}", ready)) for i in range(3)]
await asyncio.sleep(0.1)
print("setting event")
ready.set()
await asyncio.gather(*tasks)
asyncio.run(main())All three waiters print "waiting", then the main task sets the event, then all three print "started". If the event is already set, wait() returns immediately, so it does not matter whether the waiter or the setter runs first. This is why an Event is safer than a bare boolean variable that tasks poll in a loop.
Common uses are a "ready" signal after startup work, and a shutdown flag. A worker loop can check stop.is_set() between items, and the main task calls stop.set() to ask for a graceful exit. This is gentler than cancellation, because the worker decides when it is safe to stop.
An Event carries no data and wakes everyone. If you need to hand values from one task to another, use a queue, covered in the next chapter.
Semaphore: limiting concurrency
A Semaphore holds a counter. async with sem: decrements it on entry and increments it on exit. When the counter is zero, the next task waits until another task leaves. Semaphore(2) therefore allows at most two tasks inside the block at once.
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())The output is [0, 1, 2, 3, 4, 5]. Six tasks start, but only two sleep at a time, so the run takes about 0.3 seconds instead of 0.1. gather still returns results in the order you passed the awaitables, regardless of which finished first.
To see the cap working, track how many tasks are inside the block:
import asyncio
active = 0
peak = 0
async def worker(sem, n):
global active, peak
async with sem:
active += 1
peak = max(peak, active)
await asyncio.sleep(0.1)
active -= 1
return n
async def main():
sem = asyncio.Semaphore(2)
await asyncio.gather(*(worker(sem, n) for n in range(6)))
print("peak concurrency:", peak)
asyncio.run(main())This prints peak concurrency: 2. The counter updates need no lock because there is no await between reading and writing them.
What a semaphore does not limit
A semaphore limits how many tasks are inside the guarded block. It does not limit how many tasks exist. In the examples above, all six tasks are created immediately, and four of them sit waiting. With 100,000 items you would create 100,000 task objects, each holding memory. For large inputs, start a fixed number of worker tasks that pull from a queue instead. That pattern is the next chapter.
Put the async with sem: around only the operation you want to cap, such as the HTTP request. If you wrap a whole function that also does unrelated slow work, you reduce throughput for no reason.
BoundedSemaphore
asyncio.BoundedSemaphore behaves the same, but raises ValueError if release() is called more times than acquire(). A plain Semaphore silently lets the counter grow past its starting value, which hides bugs when you call acquire and release by hand. Prefer async with, which always pairs them, and use BoundedSemaphore when you must call them manually.
Cancellation and waiting tasks
Waiting on a primitive is an await, so it is a cancellation point. If a task is cancelled while waiting for a lock or semaphore, CancelledError is raised there, and the task never got the resource, so nothing needs releasing. If it is cancelled while inside async with, the context manager releases the resource as the exception propagates. This is the main reason to prefer async with over manual acquire and release.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Awaiting a long operation while holding a `Lock` | Other tasks stall behind it | Narrow the locked block to the read and write |
| Acquiring a `Lock` twice in one task | The program hangs | Restructure so the inner function does not lock |
| Forgetting `await` on `event.wait()` | A "coroutine was never awaited" warning, and no waiting | Write `await event.wait()` |
| Calling `event.set()` and then `event.clear()` with no await between | Waiters never see the flag | Waiters wake only when the loop runs, so keep the flag set long enough |
| Creating a `Semaphore` for the wrong scope | Concurrency limit is not shared | Create one and pass it to every task that shares the limit |
| Using these primitives from another thread | Undefined behaviour | Use `loop.call_soon_threadsafe` or `asyncio.run_coroutine_threadsafe` |
In Python 3.10 and later these primitives bind to the running event loop when first used, so you can create them at module level. Create them inside a coroutine or after asyncio.run starts if you want to stay portable and clear about ownership.
Exercise
A program creates 1,000 tasks, each wrapped in async with sem: where sem = asyncio.Semaphore(5). Two things might concern you: how many tasks run the guarded block at once, and how many task objects exist. What are the two numbers, and what pattern avoids the second cost?
Show answer
At most 5 tasks run the guarded block at once, but all 1,000 task objects exist from the start, with 995 suspended waiting for the semaphore. To avoid creating them all, start a fixed number of worker tasks (for example 5) that pull items from an asyncio.Queue, so only as many tasks exist as workers.
Exercise
Why does the withdraw example without a lock print 90, not 50, even though everything runs on one thread?
Show answer
Each task reads balance (100) before the await asyncio.sleep(0.01). The event loop then runs the other tasks, and they all read 100 too. Each task writes 100 - 10 = 90 after waking, so the earlier updates are overwritten. The await between the read and the write allows the interleaving. A Lock around the whole read-modify-write prevents it.