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 coroutine
  • await — suspends current coroutine, yields to event loop
  • asyncio.run() — creates and runs the event loop
  • asyncio.create_task() — schedules concurrent coroutine
  • asyncio.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 concurrently

IoT use: run sensor reading, MQTT publishing, and command listening concurrently in one thread.

See Also