asyncio : un seul thread, coopératif asyncio: a single thread, cooperative

Le GIL libère un thread pendant l'attente réseau — mais un seul thread suffit, du moment qu'il sait rendre la main de lui-même. asyncio construit exactement ça : une boucle d'événements qui exécute des milliers de tâches en attente sans jamais ouvrir un seul thread supplémentaire. Le prix : un seul appel bloquant, oublié dans une coroutine, gèle toute la boucle d'un coup. The GIL frees a thread during a network wait — but a single thread is enough, as long as it knows how to hand back control on its own. asyncio builds exactly that: an event loop running thousands of waiting tasks without ever opening a single extra thread. The price: one blocking call, forgotten inside a coroutine, freezes the entire loop at once.

Audience
Dev qui a mis un time.sleep() dans une coroutine async et se demande pourquoi tout le reste du programme s'est figé Dev who put a time.sleep() inside an async coroutine and wonders why the rest of the program froze
ChapitresChapters
5
LectureReading
≈ 20 min
NiveauLevel
●●●●
Date
Juil 2026 Jul 2026

asyncioCoroutinesEvent loop

SommaireContents ·
№ 01CadrageFraming3 min

Le GIL libérait un thread pendant l'attente. asyncio pousse l'idée plus loin : un seul thread suffit.The GIL freed a thread during the wait. asyncio pushes the idea further: a single thread is enough.

Le numéro précédent a montré que le threading accélère l'I/O parce que le GIL se relâche pendant l'attente d'une réponse réseau. Mais ouvrir un thread par requête a un coût — mémoire, création, bascule gérée par l'OS — qui devient prohibitif à mesure que le nombre de tâches en attente grandit. asyncio pose une question différente : si le seul moment utile est celui où une tâche redevient active, pourquoi ouvrir un thread du tout ? Une coroutine occupe une fraction de la mémoire d'un thread, et sa bascule est gérée entièrement en Python, par une boucle d'événements, dans un unique thread. Ce numéro explique comment cette coopération fonctionne — et son prix.The previous issue showed that threading speeds up I/O because the GIL releases during a network response wait. But opening a thread per request has a cost — memory, creation, OS-managed switching — that becomes prohibitive as the number of waiting tasks grows. asyncio asks a different question: if the only useful moment is when a task becomes active again, why open a thread at all? A coroutine takes a fraction of a thread's memory, and its switching is handled entirely in Python, by an event loop, within a single thread. This issue explains how that cooperation works — and its price.

Mille requêtes : mille threads, ou mille coroutines dans un seul threadA thousand requests: a thousand threads, or a thousand coroutines in one thread
# n°22 : un thread par requête -- l'OS bascule entre eux
import threading
def telecharger_thread(url): ...
threads = [threading.Thread(target=telecharger_thread, args=(u,)) for u in urls]
# 1000 urls -- 1000 threads -- coût mémoire et coût de bascule réels

# ici : une seule coroutine par requête -- asyncio bascule entre elles,
# dans UN SEUL thread, sans jamais demander à l'OS de changer de thread
import asyncio
# session : un client HTTP asynchrone, par exemple aiohttp.ClientSession()
async def telecharger(url):
    async with session.get(url) as resp:
        return await resp.text()

async def main():
    taches = [telecharger(u) for u in urls]
    return await asyncio.gather(*taches)
# 1000 urls -- 1000 coroutines -- un seul thread, une seule boucle
Le mot qui compte : coopératifThe word that matters: cooperative

Un thread peut être interrompu à tout moment par l'OS, sans son accord. Une coroutine ne rend la main que là où elle contient await, et nulle part ailleurs — la coopération est explicite, écrite dans le code, jamais imposée de l'extérieur.A thread can be interrupted by the OS at any moment, without its consent. A coroutine only hands back control where it contains await, and nowhere else — the cooperation is explicit, written into the code, never imposed from outside.

№ 02La surpriseThe surprise4 min

Cinq attentes d'une seconde chacune — un seul thread, une seule seconde au total.Five one-second waits each — a single thread, one second total.

La surprise n'est pas qu'asyncio soit rapide au sens du n°22 — un seul thread ne calcule jamais plus vite qu'un autre. La surprise est que cinq attentes indépendantes, qui bloqueraient un programme séquentiel pendant cinq secondes cumulées, se chevauchent presque totalement sous asyncio : dès qu'une coroutine atteint un await, elle rend explicitement la main à la boucle d'événements, qui en profite pour avancer les quatre autres tâches en attente. Le temps total se rapproche de la plus longue attente individuelle, pas de leur somme — cinq threads y arriveraient aussi, puisque le GIL est relâché pendant l'attente (n°22) ; mais un thread par tâche coûte de la mémoire et des bascules gérées par l'OS, et devient prohibitif à des milliers de tâches, là où une coroutine ne pèse presque rien.The surprise isn't that asyncio is fast in the sense of issue №22 — a single thread never computes faster than another. The surprise is that five independent waits, which would block a sequential program for a cumulative five seconds, overlap almost entirely under asyncio: as soon as a coroutine reaches an await, it explicitly hands back control to the event loop, which uses that moment to advance the four other waiting tasks. The total time approaches the single longest wait, not their sum — five threads would manage it too, since the GIL is released while waiting (issue №22); but one thread per task costs memory and OS-managed switches, and becomes prohibitive at thousands of tasks, where a coroutine weighs next to nothing.

~5 secondes -- chaque attente bloque tout le reste~5 seconds -- each wait blocks everything else
import time

def attendre_reponse(id):
    time.sleep(1)   # simule une requête réseau d'1 seconde
    return f"réponse {id}"

debut = time.perf_counter()
resultats = [attendre_reponse(i) for i in range(5)]
print("séquentiel :", time.perf_counter() - debut)
# ~5 secondes -- chaque attente bloque tout le programme, l'une après l'autre
Un seul thread qui sait quand rendre la main bat mille threads qui attendent qu'on la leur reprenne de force.A single thread that knows when to yield control beats a thousand threads waiting to have it forcibly taken back.
№ 03La mécaniqueThe mechanics5 min

Une coroutine est un générateur qui se suspend sur await au lieu de yield.A coroutine is a generator that suspends on await instead of yield.

Appeler une fonction définie avec async def ne l'exécute pas : ça crée un objet coroutine, en attente, exactement comme appeler une fonction génératrice créait un objet générateur suspendu (n°10-11) sans exécuter son corps. Rien n'avance tant qu'un moteur ne le décide pas — pour un générateur, next() ; pour une coroutine, la boucle d'événements d'asyncio. Chaque await à l'intérieur d'une coroutine est un point de suspension explicite : la boucle reprend la main à cet instant précis, avance les autres tâches en attente, puis revient reprendre celle-ci exactement là où elle s'était arrêtée, avec tout son état local intact — le même mécanisme que le yield d'un générateur suspendu au n°21, appliqué à la concurrence plutôt qu'à l'itération paresseuse.Calling a function defined with async def doesn't execute it: it creates a waiting coroutine object, exactly like calling a generator function created a suspended generator object (issues №10-11) without running its body. Nothing advances until some engine decides to — for a generator, next(); for a coroutine, asyncio's event loop. Every await inside a coroutine is an explicit suspension point: the loop takes back control at that exact instant, advances the other waiting tasks, then comes back to resume this one exactly where it stopped, with all its local state intact — the same mechanism as a suspended generator's yield from issue №21, applied to concurrency instead of lazy iteration.

Appeler une coroutine ne l'exécute pas -- ça crée juste l'objetCalling a coroutine doesn't run it -- it just creates the object
import asyncio

async def dire_bonjour():
    print("avant l'attente")
    await asyncio.sleep(1)
    print("après l'attente")

c = dire_bonjour()
print(type(c))   # <class 'coroutine'> -- appeler une fonction async NE
                   # L'EXÉCUTE PAS, exactement comme appeler une fonction
                   # génératrice ne fait que créer l'objet générateur (n°10-11)

# c reste un objet en attente tant que rien ne la fait avancer :
asyncio.run(c)   # ici seulement, le corps s'exécute réellement
La boucle bascule entre tâches à chaque await, jamais ailleursThe loop switches between tasks at every await, nowhere else
import asyncio

async def tache(nom, delai):
    print(f"{nom} démarre")
    await asyncio.sleep(delai)   # SUSPEND cette coroutine, rend la main
                                  # à la boucle -- exactement comme yield
                                  # suspendait un générateur au n°21
    print(f"{nom} termine")

async def main():
    # la boucle d'événements planifie les trois coroutines, et bascule
    # entre elles à chaque await -- jamais au milieu d'une ligne de code
    await asyncio.gather(
        tache("A", 2),
        tache("B", 1),
        tache("C", 3),
    )

asyncio.run(main())
# ordre observé : A démarre, B démarre, C démarre, B termine (1s),
# A termine (2s), C termine (3s) -- un seul thread, jamais deux lignes
# de code Python actives en même temps
Ce que garantit un thread uniqueWhat a single thread guarantees

Entre deux await, aucune autre coroutine ne peut s'exécuter : le code qui sépare deux points de suspension tourne de façon atomique, sans risque qu'une autre tâche modifie un état partagé au milieu. C'est un avantage réel d'asyncio sur le threading — à condition qu'aucun await ne manque là où il faudrait.Between two await points, no other coroutine can run: the code separating two suspension points runs atomically, with no risk of another task modifying shared state midway. That's a real advantage of asyncio over threading — provided no await is missing where one is actually needed.

№ 04Le piègeThe trap4 min

Un seul appel bloquant, oublié dans une coroutine, gèle toute la boucle — pas seulement cette tâche.One blocking call, forgotten inside a coroutine, freezes the entire loop — not just that task.

Le piège découle directement de ce qui fait la force d'asyncio : un seul thread. Un appel bloquant classique — time.sleep(), une requête réseau synchrone avec requests, une lecture disque non-async — ne contient aucun await : il ne rend jamais la main à la boucle d'événements, il bloque le thread entier jusqu'à sa fin. Comme ce thread est le seul que la boucle possède, absolument toutes les autres tâches en attente — même celles qui n'ont rien à voir avec l'appel bloquant — restent gelées pendant toute sa durée. Le programme redevient séquentiel malgré des dizaines de coroutines apparemment concurrentes, sans qu'aucune erreur ne le signale.The trap follows directly from what makes asyncio strong: a single thread. A classic blocking call — time.sleep(), a synchronous network request with requests, a non-async disk read — contains no await: it never hands back control to the event loop, it blocks the entire thread until it finishes. Since that thread is the only one the loop owns, absolutely every other waiting task — even ones unrelated to the blocking call — stays frozen for its entire duration. The program turns sequential again despite dozens of apparently concurrent coroutines, with no error signaling it.

B et C attendent leur tour alors qu'ils n'avaient rien demandéB and C wait their turn even though they asked for nothing
import asyncio, time

async def tache(nom, delai):
    print(f"{nom} démarre")
    time.sleep(delai)   # PIÈGE -- bloquant, pas de await : ne rend
                          # JAMAIS la main à la boucle d'événements
    print(f"{nom} termine")

async def main():
    await asyncio.gather(
        tache("A", 2),
        tache("B", 1),
        tache("C", 1),
    )

asyncio.run(main())
# ordre observé : A démarre, A termine (2s), B démarre, B termine (1s),
# C démarre, C termine (1s) -- total ~4s, comme du séquentiel PUR.
# time.sleep() ne suspend pas la coroutine -- il bloque tout le thread,
# donc TOUTE la boucle, y compris les tâches B et C qui n'ont rien
# demandé et attendaient déjà leur tour.
Le réflexe à retenirThe reflex to keep

Dans une fonction async def, tout appel qui peut prendre du temps doit avoir un await devant lui, avec une version non-bloquante de la bibliothèque concernée. S'il n'en existe pas, asyncio.to_thread() délègue l'appel bloquant à un thread séparé, pour ne pas geler la boucle entière.Inside an async def function, any call that can take time needs an await in front of it, using a non-blocking version of the relevant library. If none exists, asyncio.to_thread() delegates the blocking call to a separate thread, so it doesn't freeze the entire loop.

№ 05Bilan & éditoRecap & editorial2 min

Ce numéro en une tableThis issue in one table

№No.TitreTitleTensionTension
23asyncio : un seul thread, coopératifasyncio: a single thread, cooperativeLa boucle d'événements ; await comme point de suspension ; l'appel bloquant qui gèle toutThe event loop; await as a suspension point; the blocking call that freezes everything
Un seul thread ne pardonne rien. Un appel qui oublie de rendre la main ne bloque pas une tâche — il bloque toutes les autres.A single thread forgives nothing. A call that forgets to hand back control doesn't block one task — it blocks every other one.
Prochain numéro — №24, clôture du Volume VIIINext issue — No. 24, closing Volume VIII

Ce numéro a montré qu'appeler une coroutine ne l'exécute pas — ça crée seulement l'objet en attente. Le №24 pousse cette mécanique jusqu'à son piège le plus silencieux : coro() sans await ne s'exécute jamais, sans la moindre erreur visible ; et une tâche créée avec create_task sans référence gardée peut disparaître avant même d'avoir eu la chance de s'exécuter.This issue showed that calling a coroutine doesn't execute it — it only creates the waiting object. No. 24 pushes that mechanic to its most silent trap: coro() without await never runs, with no visible error at all; and a task created with create_task without a kept reference can vanish before it ever gets the chance to run.