asyncio
Python’s built-in library for concurrent I/O-bound programming using an event loop.
Concurrent, not parallel: one thread, tasks take turns. While one task waits (I/O, sleep, network), others run. Total CPU work is the same — less idle time.
Core elements:
async def— declares a coroutineawait— suspends current coroutine, yields to event loopasyncio.run()— creates and runs the event loopasyncio.create_task()— schedules concurrent coroutineasyncio.gather()— runs multiple coroutines concurrently, waits for all
import asyncio
async def task():
await asyncio.sleep(1) # yields to event loop
asyncio.run(asyncio.gather(task(), task())) # both run concurrentlyIoT use: run sensor reading, MQTT publishing, and command listening concurrently in one thread.
See Also
- Async Python topic