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并没有休眠,而只是设置了一个定时器,然后就去执行别的代码,等时间到,则再回到这里继续执行。