first comit
This commit is contained in:
56
demo_concurrence/2_async_simulation.py
Normal file
56
demo_concurrence/2_async_simulation.py
Normal file
@@ -0,0 +1,56 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
import time
|
||||
|
||||
# --- Configuration ---
|
||||
NUM_TASKS = 15
|
||||
SLEEP_DURATION = 0.2 # Chaque tâche "attendra" 0.2 seconde
|
||||
|
||||
|
||||
# --- Fonctions ---
|
||||
def setup_logging():
|
||||
"""Configure un logging simple pour la sortie console."""
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
|
||||
|
||||
# TODO 1 : remplacer "def" par "async def"
|
||||
def worker_task_async(task_id: int):
|
||||
"""
|
||||
Une coroutine qui simule un travail non-bloquant.
|
||||
await asyncio.sleep() ne gèle pas le programme. Il notifie la boucle
|
||||
d'événements qu'elle peut exécuter autre chose pendant cette pause.
|
||||
"""
|
||||
logging.info(f"Tâche {task_id}: Démarrage...")
|
||||
|
||||
# TODO 2 : remplacer "time.sleep" par "await asyncio.sleep"
|
||||
|
||||
logging.info(f"Tâche {task_id}: Terminée.")
|
||||
return f"Résultat de la tâche {task_id}"
|
||||
|
||||
|
||||
async def main():
|
||||
"""Fonction principale (coroutine) du script asynchrone."""
|
||||
setup_logging()
|
||||
logging.info("--- DÉMARRAGE DE LA SIMULATION ASYNCHRONE ---")
|
||||
|
||||
start_time = time.perf_counter()
|
||||
|
||||
# TODO 3 : créer une liste de tâches en appelant worker_task_async, puis utiliser asyncio.gather
|
||||
|
||||
|
||||
duration = time.perf_counter() - start_time
|
||||
|
||||
logging.info("-" * 50)
|
||||
logging.info(f"Exécution ASYNCHRONE terminée en {duration:.2f} secondes.")
|
||||
logging.info(f"Temps attendu : proche de la durée d'une seule tâche ({SLEEP_DURATION}s).")
|
||||
logging.info("Les temps d'attente ont été gérés en parallèle.")
|
||||
logging.info("-" * 50)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user