11. Asyncio¶
So far every script in the tutorial has been sequential – one line runs at a time, and a call that has to wait (a sensor read, a network round-trip, a snapshot) blocks the script until it finishes. That works while there is only one thing to do. The moment an application needs to do several things at once – run a snapshot loop and answer a serial command, and upload frames over the network – a sequential script breaks down. The first slow call stops everything else from making progress.
The asyncio module is MicroPython’s answer. It lets
the application describe several jobs as separate
coroutines and runs them concurrently on a single thread,
cooperatively – whichever coroutine is currently running
yields control back to the scheduler whenever it has to
wait. A snapshot loop, a UART reader, and a network client
can all live in the same script and the slow parts of one no
longer freeze the others.
The pages ahead cover the async/await keywords and
the Task lifecycle, coordination through
gather() and wait_for(),
cancellation and exception propagation, the three built-in
synchronisation primitives (Event,
Lock, ThreadSafeFlag),
the language hooks for plugging application classes into
asyncio idioms, a small CSI wrapper that lets
snapshot() run as a coroutine, and the common
pitfalls that come with cooperative scheduling.
Coordination
Synchronisation primitives
Custom async objects
Loop control
Frame capture
Pitfalls
Wrap up