Discuss / Python / 关于 yield from asyncio.sleep(1.0)

关于 yield from asyncio.sleep(1.0)

Topic source

大家好,根据我的理解,当正在被主线程执行的的coroutine遇到 yield from语句时,当前coroutine会被挂起,yield from 后面的coroutine 会被主线程执行。

那为什么yield from asyncio.sleep(1.0)这个语句里面的 sleep不会被主线程执行? 是谁在执行这个休眠语句?asyncio内部难道还有一个线程池?

下面这个就是我的例子,当print_sum遇到yield from被挂起时,yield from后面的compute就会被主线程执行 @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

"当asyncio.sleep()返回时,线程就可以从yield from拿到返回值(此处是None),然后接着执行下一行语句。"

这里讲的不是很清楚,asyncio.sleep() 并没有休眠,而是包装了一个计时器,丢到queue里面, while循环内部会判断这个计时器是否超时,若超时,就会执行asyncio.sleep()所在的那个,被挂起的coroutine 这样理解起来就容易一些了

灵剑2012

#3 Created at ... [Delete] [Delete and Lock User]

Sleep并不是一个coroutine而是一个future,future大致上相当于一个回调机制,当发生这个过程之后会主动回调你的coroutine让coroutine继续执行,所以不会占用CPU时间


  • 1

Reply