等待关键字如何工作? [英] How await keyword works?

查看:79
本文介绍了等待关键字如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于给定的以下协程(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 awaits 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)

这篇关于等待关键字如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆