yield from语句

result = yield from B()
# B是一个coroutine

yield from将调用一个子协程(也就是在一个协程中调用另一个协程)并直接获得子协程的返回结果。
当正在被主线程执行的的coroutine遇到 yield from语句时,当前coroutine会被挂起,yield from 后面的coroutine 会被主线程执行。

例子
import asyncio
@asyncio.coroutine
def print_sum(x, y):
    result = yield from compute(x, y)
    print("%s + %s = %s" % (x, y, result))

@asyncio.coroutine
def compute(x, y):
    print("Compute %s + %s ..." % (x, y))
    yield from asyncio.sleep(1.0)
    return x + y

在这个例子,当print_sum遇到yield from被挂起时,yield from后面的compute就会被主线程执行

yield from asyncio.sleep(1) 
#这里CPU并没有休眠,而只是设置了一个定时器,然后就去执行别的代码,等时间到,则再回到这里继续执行。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值