问题描述
对于给定的以下协程(f
),
For a given below co-routine(f
),
import csv
import urllib
def f(resp):
print('Line 1')
yield csv.reader(resp.read().decode('utf-8'))
def h():
url = 'http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NYSE&render=download'
resp = urllib.urlopen(url)
cr = f(resp)
cr = f(resp)
将迭代器对象分配给cr
,
cr = f(resp)
assigns an iterator object to cr
,
cr.next()
执行第1行,并在yield关键字处阻塞.
cr.next()
execute Line 1 and block at yield keyword.
我的理解是,使用语法cr=f(resp)
,在后台没有带线程的事件循环(任务调度程序)
My understanding is, with syntax cr=f(resp)
there is no event-loop(task scheduler) with threading, behind the scene
而不是说cr=f(resp)
(上面),如果相同的函数(h
)具有await f(resp)
如下所述(await
关键字要求async
语法),
Instead of saying cr=f(resp)
(above), If the same function(h
) has await f(resp)
as mentioned below(await
keyword asks for async
syntax),
async def h_async():
url = 'http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=NYSE&render=download'
resp = urllib.urlopen(url)
await f(resp)
然后
await f(resp)
与cr=f(resp)
有何不同?
h_async()
与h()
有何不同?如本示例await关键字是否在后台引入了带有线程的事件循环(任务调度程序)? rel ="nofollow noreferrer">代码
How h_async()
different from h()
? Does await
keyword introduce event-loop(task scheduler) with threading, behind the scene, as shown in this sample code
推荐答案
await EXPR
表示事件任务计划程序可以在此步骤打开其他功能(例如,从任务队列中拉出已准备好的内容),并指出等待EXPR
.如果EXPR
是协程,则意味着它可以包含后续的await
,并且当此协程处于非阻塞等待状态(例如IO或网络响应,睡眠等)时,同样可以执行其他操作
await EXPR
means event tasks scheduler can switch on something other at this step (for example, pull something that's ready from the task queue), and also indicates that EXPR
is awaitable. If EXPR
is a coroutine, it means it can have subsequent await
s inside, and again something else can be also executed when this coroutine is in non-blocking waiting state (like IO or network response, sleep, etc)
这篇关于等待关键字如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!