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.run(), the keyword
asyncwill 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
- 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
asyncto create a coroutine method
awaitto call another coroutine
_A_will into wait status until
_B_execute finish and notify.
asyncio.run()to submit a coroutine
Create Task & Submit Coroutine
asyncio.create_task()will submit a coroutine into Task Queue
_task_1_be execute, main thread will keep waiting until
await, and so on
- It have concurrency effect like as multi threading( or multi processing )
Timeout & Cancel
Task.done()to determine a task is finish or not yet.
Task.cancel()to cancel a task which is executing.
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
asyncio.gather(task1, task2, …, taskN)
- Add parameter
return_exceptions = Truecapture exception result