await, Tasks, and Gathering
Use await, asyncio.create_task, and asyncio.gather for concurrency.
await vs Sequential
Using await alone runs coroutines sequentially. To run them concurrently, wrap them in Tasks.
import asyncio
async def main():
# Sequential — total ~3 s
await asyncio.sleep(2)
await asyncio.sleep(1)
# Concurrent using gather — total ~2 s
await asyncio.gather(asyncio.sleep(2), asyncio.sleep(1))asyncio.create_task()
asyncio.create_task(coro) schedules a coroutine to run as an independent Task concurrently with the current coroutine.
import asyncio
async def work(n):
await asyncio.sleep(n)
return n
async def main():
t1 = asyncio.create_task(work(2))
t2 = asyncio.create_task(work(1))
r1 = await t1
r2 = await t2
print(r1, r2) # 2 1 (total ~2 s)
asyncio.run(main())All lessons in this course
- Coroutines and the event loop
- await, Tasks, and Gathering
- Async Context Managers and Iterators
- Async I/O Patterns in Production