再次理解asyncio/await syntax and asyncio in Python

Quant_Learner發表於2020-12-19
  • Overview

    asynchronous : 非同步

    concurrent : 併發

    coroutine : 協程

    thread : 執行緒

    parallelism : 並行

    multiprocess : 多程式

  • asyncio/await syntax

    PEP492 – Coroutines with async and await syntax

    The PEP492 is proposed to make coroutines a proper standalone concept in Python, and introduce new supporting syntax. The ultimate goal is to help establish a common, easily approachable, mental model of asynchronous programming in Python and make it as close to synchronous programming as possible.

    Current Python supports implementing coroutines via generators (PEP342), further enhanced by the yield from syntax introduced in PEP 380.

  • New Coroutine Declaration Syntax

    the following new syntax is used to declare a native coroutine:

    async def read_data(db):
        pass
    

    Key properties of coroutines:

    • async def functions are always coroutines, even if they do not contain await expressions.
    • It is a SyntaxError to have yield or yield from expressions in an async function.
  • Await Expression

    The following new await expression is used to obtain a result of coroutine execution :

    async def read_data(db):
        data = await db.fetch("select ...")
        ...
    

    await, similarly to yield from, suspends execution of read_data coroutine until db.fetch awaitable completes and returns the result data.

    《理解awaitable in Python》

    It is a SyntaxError to use await outside of an async def function.

    It is a TypeError to pass anything other than an awaitable object to an await expression.

  • Asynchronous Context Managers and “async with

    An asynchronous context manager is a context manager that is able to suspend execution in its enter and exit methods.

    It is a SyntaxError to use async with outside of an async def function.

  • asyncio - Asynchronous I/O

    廖雪峰的官方網站

    Async IO in Python: A Complete Walkthrough

    asyncio is a library to write concurrent code using the async/await syntax.

    asyncioPython3.4引入的標準庫,async/awaitPython3.5引入的針對asyncio的新語法。

    asyncio的程式設計模型是一個訊息迴圈,從模型中直接獲取一個EventLoop,然後把需要執行的攜程扔到EventLoop中執行,實現非同步。

    訊息迴圈中有多個任務[a,b,c]:

    1. 首先執行第一個任務a,過程中遇到a內部的yield from或者await,a任務相當於continue,後續先不執行,等待await後面awaitful物件執行完成
    2. b任務執行,同樣的遇到await之後continue b
    3. a任務中await任務完成,繼續執行a過程後面的任務
    4. 如此繼續

    不同coroutine是由同一個thread執行,即asyncio可以實現單執行緒併發IO操作。

  • Low-level APIs

    Event loop is the core of every asyncio application. Event loops run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.

相關文章