[Python3] asyncio

Zheng-Wei, Liu
3 min readDec 22, 2022
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 ?

  1. 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() or asyncio.run() , the keyword async will packet methods as coroutine.
  2. 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 .
  3. 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.
  4. 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
Simply to define 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 )
Create task for asyncio for concurrency

Timeout & Cancel

  • Using Task.done() to determine a task is finish or not yet.
  • Using Task.cancel() to cancel a task which is executing.
Cancel task
  • Using asyncio.wait_for(task, timeout=wait_duration) for automate cancel a task if execute timeout
Waiting for 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

Parallel multi task

  • Using asyncio.gather(task1, task2, …, taskN)
  • Add parameter return_exceptions = True capture exception result
Parallel multi task

--

--