Files
live-campus-mcs-p-2027.2/Semaine_09/Asyncio_examples/main.py
T
gauvainboiche ce1f0e513a feat: Semaine 9
2026-05-15 16:24:56 +02:00

70 lines
1.5 KiB
Python

"""
async => transforme une fonction en coroutine
=> une fonction COROUTINE peut suspendre son exécution
en cours de route et reprendre là où elle s'est
arrêtée.
await => c'est le point de suspension
=> quand une coroutine rencontre un "await", elle doit
attendre le résultat, et signale qu'une autre
coroutine peut se lancer en parallèle.
"""
import time
# A l'ancienne
section = "Séquentiel"
print(f"{"=" * len(section)}")
print(section)
print(f"{"=" * len(section)}")
def count():
print("One")
time.sleep(1)
print("Two")
time.sleep(1)
def main():
for _ in range(3):
count()
if __name__ == "__main__":
start = time.perf_counter()
main()
print(f"{__file__} exécuté en {time.perf_counter() - start:.2f} secondes.")
# Nouvelle méthode
section = "Asynchrone avec ASYNCIO"
print(f"{"=" * len(section)}")
print(section)
print(f"{"=" * len(section)}")
import asyncio
async def async_count():
print("One")
await asyncio.sleep(1)
print("Two")
await asyncio.sleep(1)
async def async_main():
await asyncio.gather(async_count(), async_count(), async_count())
if __name__ == "__main__":
start = time.perf_counter()
asyncio.run(async_main())
print(f"{__file__} exécuté en {time.perf_counter() - start:.2f} secondes.")
async def z(x):
return x
async def f(x):
y = await z(x) # si 'z' est une coroutine
return y
async def g(x):
yield x # async fonctionne sur les générateurs