Concurrency and asyncio
Wait for many slow operations at once, without threads.
Many programs spend most of their time waiting: for a web API, a database or a file. asyncio lets one thread switch to other work while it waits. It is for I/O-bound tasks, not for heavy calculation.
import asyncio
async def fetch(n):
await asyncio.sleep(1) # stands in for a network call
return n * 2
async def main():
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
print(results) # [2, 4, 6] after about 1 second, not 3
asyncio.run(main())async defdefines a coroutine. Calling it only creates the coroutine.awaitpauses it until the result is ready and lets other coroutines run.asyncio.gatherruns several at the same time.asyncio.runstarts the event loop once.
CarefulA blocking call such as time.sleep() or requests.get() inside a coroutine freezes the whole event loop. Use async libraries (httpx, aiohttp) or run the blocking call in a thread with asyncio.to_thread.
Choosing the tool
| Work | Use |
|---|---|
| Many network or disk waits | asyncio or threads |
| Heavy CPU work (maths, images) | multiprocessing or concurrent.futures.ProcessPoolExecutor |
| Simple parallel blocking calls | concurrent.futures.ThreadPoolExecutor |
NoteThe global interpreter lock (GIL) lets only one thread run Python bytecode at a time in the standard CPython build. Threads still help with I/O because they release it while waiting.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.