appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Concurrency and asyncio

Lesson 4 of 512 minAdvanced

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 def defines a coroutine. Calling it only creates the coroutine.
  • await pauses it until the result is ready and lets other coroutines run.
  • asyncio.gather runs several at the same time. asyncio.run starts 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

WorkUse
Many network or disk waitsasyncio or threads
Heavy CPU work (maths, images)multiprocessing or concurrent.futures.ProcessPoolExecutor
Simple parallel blocking callsconcurrent.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.

1. asyncio.gather(fetch(1), fetch(2), fetch(3)) with a 1 second wait each takes about:
2. What happens if you call time.sleep(5) inside a coroutine?
3. Which tool suits CPU-heavy work?

Key terms