minimal/python-asyncio

Python asyncIO

asyncio est une librairie pour écrire du code concurrent, “I/O-bound”, avec la syntaxe async / await

En CPython (implémentation standard), l’exécution d’un programme utilisant asyncio s’effectue dans un seul processus mono-thread, en utilisant le GIL.

Concept sous-jacent : coroutines

Coroutine :

  • Fonction qui peut suspendre son exécution avant le return final, pour passer le contrôle à une autre coroutine
  • des valeurs peuvent être échangées
async def g():
    # Pause here and come back to g() when f() is ready
    r = await f()
    return r

Exemple

import asyncio

async def count():
    print("One")
    await asyncio.sleep(1)
    print("Two")

async def main():
    await asyncio.gather(count(), count(), count())

if __name__ == "__main__":
    import time
    s = time.perf_counter()
    asyncio.run(main())
    elapsed = time.perf_counter() - s
    print(f"{__file__} executed in {elapsed:0.2f} seconds.")

High-level API

High-level API

Low-level API

Low-level API

Snippets

Python 3 asyncio snippets