Python & FastAPI•Part 3: Asynchronous Programming & Concurrency (26 - 40)
AsyncIO: Coroutines, Tasks, and Futures:
In Simple Words:
- Coroutine: A function declared with
async defthat can pause execution viaawait. - Task: A wrapper that schedules a coroutine to run on the event loop concurrently (
asyncio.create_task()). - Future: Low-level object representing an eventual result of an async operation.
python
async def worker(name):
print(f"Worker {name} started")
await asyncio.sleep(1)
return f"{name} done"
async def run_tasks():
# Schedules both tasks to run concurrently in background:
t1 = asyncio.create_task(worker("A"))
t2 = asyncio.create_task(worker("B"))
res = await asyncio.gather(t1, t2)
print(res)