本文主要是介绍再次理解asyncio/await syntax and asyncio in Python,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
-
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
viagenerators
(PEP342
), further enhanced by theyield from
syntax introduced inPEP 380
. -
New
Coroutine Declaration
Syntaxthe 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 containawait
expressions.- It is a
SyntaxError
to haveyield
oryield from
expressions in anasync
function.
-
Await
ExpressionThe 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 toyield from
, suspends execution ofread_data
coroutine untildb.fetch
awaitable completes and returns the result data.《理解awaitable in Python》
It is a
SyntaxError
to useawait
outside of anasync
def function.It is a
TypeError
to pass anything other than anawaitable
object to anawait
expression. -
Asynchronous Context Managers and “
async with
”An
asynchronous context manager
is a context manager that is able to suspend execution in itsenter
andexit
methods.It is a
SyntaxError
to useasync with
outside of anasync def
function. -
asyncio - Asynchronous I/O
廖雪峰的官方网站
Async IO in Python: A Complete Walkthrough
asyncio
is a library to write concurrent code using theasync/await
syntax.asyncio
是Python3.4
引入的标准库,async/await
是Python3.5
引入的针对asyncio
的新语法。asyncio
的编程模型是一个消息循环,从模型中直接获取一个EventLoop
,然后把需要执行的携程扔到EventLoop
中执行,实现异步。消息循环中有多个任务[a,b,c]:
- 首先执行第一个任务a,过程中遇到a内部的yield from或者await,a任务相当于continue,后续先不执行,等待await后面awaitful对象执行完成
- b任务执行,同样的遇到await之后continue b
- a任务中await任务完成,继续执行a过程后面的任务
- 如此继续
不同
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.
这篇关于再次理解asyncio/await syntax and asyncio in Python的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!