Vol. 8 — № 23
The Python Loop · KiosqueNewsstand
Blog  
Un atelier Python · Édition d'ApprentissageA Python Workshop · Learning Edition

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.

AudienceAudience
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
Format
Self-paced
ChapitresChapters
5
Date
Juil 2026 Jul 2026
≈ 20 min ●●●● asyncioCoroutinesEvent loop

Chapitre 1 en accès libre — la suite (ch. 2 à 5) est réservée. Chapter 1 free to read — the rest (ch. 2–5) is members-only.

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.

🔒

La suite est réservée The rest is members-only

Le premier numéro est libre. Débloque tout The Python Loop — tous les volumes, à vie — pour 5 €, paiement unique. The first issue is free. Unlock all of The Python Loop — every volume, forever — for €5, one-time.

Retour au kiosqueBack to newsstand