asyncio is a library to write concurrent code using the async/await syntax.
---- from Python3.11.1 documentation
This article is write down the note with my study of python asyncio package.
How does asyncio work ?
- The main process, which is start run by IDE or command line, have a main thread to execute submit a coroutine to asyncio event loops by
asyncio.create_task()
orasyncio.run()
, the keywordasync
will packet methods as coroutine. - The event loops will monitoring all of the submit task, and choice a not finished, current can going on coroutine to execute its task until it finish, or change status to wait when meet
await
. - When event loops meet
await
, you should be notify (or notify all) task(s) which status is waiting for blocking, and check the blocking condition is still exist or not. - Repeating above step 2 and step 3 until no more coroutines in asyncio event loops (i.e. all of the coroutine will be finish or canceled).
async & await
- Using
async
to create a coroutine method - Using
await
to call another coroutine_B_
in coroutine_A_
.
_A_
will into wait status until_B_
execute finish and notify. - Using
asyncio.run()
to submit a coroutine
Create Task & Submit Coroutine
- The
asyncio.create_task()
will submit a coroutine into Task Queue - When
await
_task_1_
be execute, main thread will keep waiting until_task_1_
finish
/await
, and so on_task_2_
- It have concurrency effect like as multi threading( or multi processing )
Timeout & Cancel
- Using
Task.done()
to determine a task is finish or not yet. - Using
Task.cancel()
to cancel a task which is executing.
- Using
asyncio.wait_for(task, timeout=wait_duration)
for automate cancel a task if execute timeout
Sometimes, we want the task keep going on their work until finish, and I just would like to know the task will happened timeout or not. For example: Counting the times of timeout to calculate performance
Gather multi task
- Using
asyncio.gather(task1, task2, …, taskN)
- Add parameter
return_exceptions = True
capture exception result