本文主要是介绍再次理解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
coroutinesviagenerators(PEP342), further enhanced by theyield fromsyntax introduced inPEP 380. -
New
Coroutine DeclarationSyntaxthe following new syntax is used to declare a
native coroutine:async def read_data(db):passKey properties of
coroutines:async deffunctions are always coroutines, even if they do not containawaitexpressions.- It is a
SyntaxErrorto haveyieldoryield fromexpressions in anasyncfunction.
-
AwaitExpressionThe following new
awaitexpression 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_datacoroutine untildb.fetchawaitable completes and returns the result data.《理解awaitable in Python》
It is a
SyntaxErrorto useawaitoutside of anasyncdef function.It is a
TypeErrorto pass anything other than anawaitableobject to anawaitexpression. -
Asynchronous Context Managers and “
async with”An
asynchronous context manageris a context manager that is able to suspend execution in itsenterandexitmethods.It is a
SyntaxErrorto useasync withoutside of anasync deffunction. -
asyncio - Asynchronous I/O
廖雪峰的官方网站
Async IO in Python: A Complete Walkthrough
asynciois a library to write concurrent code using theasync/awaitsyntax.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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!