asyncio in Python
Table of Contents
It is an event loop with callback functions in it.
An event loop is single-threaded. Therefore, stuff that goes inside the event loop should not be CPU heavy (Usually IO or HTTP request). If you have a CPU-heavy task. You can have an executor that runs this task in a separate thread/process and wait for the result in the event loop.
thread vs asyncio
- thread use lock to tell where it is impossible to go to another task.
- asyncio use await to tell where is ti possible to go to another task.
async def f
it defines a coroutine. If you call f()
directly, the return is a coroutine object.
asyncio.createtask(coroutine)
- Wrap a coroutine into a task.
- It creates a copy of the context for later execution.
- Put the task into the event loop. It will not start executing until the interpreter reaches an
await
statement.
await
- Block: register the stuff afterward as a callback in the event loop. It will be executed after await's result/timer comes back.
- waiting part:
await coroutine1
: run coroutine1 immediately in the current context.await task1
: go back to the event loop and execute the next function. if task1 is not on top of the event loop, it may not be the next to execute.