asyncio offers concurrency in a single thread. Instead of the operating system switching threads whenever it wants, you decide where switching can happen: at each await. This removes almost all race conditions (between one await and the next nobody interrupts you) and makes it possible to handle thousands of I/O tasks with very little memory.
Coroutines: async and await
A function defined with async def is a coroutine: calling it does not run anything, it returns an object that someone must run. Inside it, await suspends the coroutine until what it waits for is ready and lets the event loop run others. asyncio.run(main()) starts the loop.
# Not run in the browser corrector (it does not allow asyncio.run).
import asyncio
async def download(name, pause):
print("starts", name)
await asyncio.sleep(pause) # yields control while waiting
print("ends", name)
return name.upper()
async def main():
results = await asyncio.gather(
download("a", 0.1),
download("b", 0.05),
)
print(results)
asyncio.run(main())
# starts a
# starts b
# ends b
# ends a
# ['A', 'B']
Look at the output order: both downloads start at the same time and the shorter one ends first. With gather the total time is that of the slowest one (0.1 s), not the sum.
Tasks with create_task
asyncio.create_task(coroutine) schedules a coroutine to run right away, in the background, and returns a task you can await later. It is the way to launch several things and carry on with another.
# Not run in the browser corrector (it does not allow asyncio.run).
import asyncio
async def count(name, n):
for i in range(1, n + 1):
await asyncio.sleep(0.05)
print(name, i)
async def main():
t1 = asyncio.create_task(count("x", 2)) # scheduled right away
t2 = asyncio.create_task(count("y", 2))
await t1
await t2
asyncio.run(main())
# x 1
# y 1
# x 2
# y 2
A classic mistake: blocking the loop
A time.sleep() or a long calculation inside a coroutine blocks the whole loop: nobody else advances. Always use the asynchronous version (await asyncio.sleep()) or move the heavy work to another thread or process (asyncio.to_thread).
Limiting and controlling
As with threads, there are asyncio.Lock, asyncio.Semaphore, asyncio.Queue and asyncio.Event, used with async with / await. A semaphore limits how many coroutines get in at once, for example to avoid overloading a server:
# Not run in the browser corrector (it does not allow asyncio.run).
import asyncio
async def use(name, sem):
async with sem: # at most 2 at a time
print("enters", name)
await asyncio.sleep(0.05)
print("leaves", name)
async def main():
sem = asyncio.Semaphore(2)
await asyncio.gather(*(use(n, sem) for n in "abc"))
asyncio.run(main())
# enters a
# enters b
# leaves a
# leaves b
# enters c
# leaves c
And asyncio.wait_for sets a time limit:
# Not run in the browser corrector (it does not allow asyncio.run).
import asyncio
async def slow():
await asyncio.sleep(1)
async def main():
try:
await asyncio.wait_for(slow(), timeout=0.05)
except asyncio.TimeoutError:
print("Too slow") # Too slow
asyncio.run(main())
In Python 3.11 or later, asyncio.TaskGroup groups tasks and guarantees that they all finish (or that, if one fails, the others are cancelled).
How it works inside
An event loop is, in essence, a schedule of sleeping tasks: it stores when each one must wake up and always resumes the one that is due first. This minimal version uses generators and a virtual clock, and runs in the corrector:
import heapq
def task(name, pauses):
for p in pauses:
yield p # "sleep p units"
schedule = []
clock = 0
for order, (name, pauses) in enumerate([("a", [3]), ("b", [1, 1])]):
gen = task(name, pauses)
heapq.heappush(schedule, (next(gen), order, name, gen))
while schedule:
wakes, order, name, gen = heapq.heappop(schedule)
clock = wakes
print(f"t={clock} {name}")
try:
heapq.heappush(schedule, (clock + next(gen), order, name, gen))
except StopIteration:
pass
# t=1 b
# t=2 b
# t=3 a
You write the full version, with several pauses per task, in Event loop with a virtual clock.