- def __iter__(self):
- if not self.done():
- self._asyncio_future_blocking = True
- yield self # This tells Task to wait for completion.
- assert self.done(), "yield from wasn't used with future"
- return self.result() # May raise too.
- if compat.PY35:
- __await__ = __iter__ # make compatible with 'await' expression
留意这里的 yield self !也就是说 future 在第一次履行到这里时,会暂停履行并返回它本身,因为 coroutine 中应用的都是 yield from/await (它们在接收的参数上有差别,但在本文的评论辩论中没有差别),是以这个值会一向向上传递,到 Task._step 函数的 result = coro.send(None) 这里,那我们来看看 Task 对 result 做了什么,重要的是 这一句 :
- result.add_done_callback(self._wakeup)
也就是说 task( print_sum ) 获得了最内层暂停的 sleep 生成的 future 并为该 future 注册了一个回调,使得在 future.set_result 被调用时, task._wakeup 会被调用。这部分的逻辑可以看 这里 。
我们再回过火来看看 future.set_result 会在什么时刻被调用,在 asyncio.sleep 函数里,我们为 event loop 注册了一个回调函数:
- h = future._loop.call_later(delay,
- futures._set_result_unless_cancelled,
- future, result)
那么这个 _set_result_unless_cancelled 是如许的:
- def _set_result_unless_cancelled(fut, result):
- """Helper setting the result only if the future was not cancelled."""
- if fut.cancelled():
- return
- fut.set_result(result)
这里 poll_events 之前,会去计算所有急鹞鲼事宜起码须要等待的时光,这个时光内即使没有事宜产生, poll_events 也会退出,以便触发急鹞鲼事宜。 _process_timeout_events 函数的感化是比较当前时光与急鹞鲼的目标履行时光,如不雅目标履行时光已经达到,则履行响应的回调函数。
是以,所有的流程应当是如许的:
【编辑推荐】
- 应用Python和Asyncio编写在线多人游戏(一)
- 应用Python和Asyncio编写在线多人游戏(二)
- 应用Python和Asyncio编写在线多人游戏(三)
- Python 中的异步编程:Asyncio
- Python中的异步编程:Asyncio
小结
那么 asyncio 做为一个库,做了什么,没做什么?
- 控制流的暂停与恢复,这是经由过程 Python 内部的 Generator(生成器)相干的功能实现的。
- 协程链,即把不合协程链链接在一路的机制。依旧是经由过程 Python 的内置支撑,即 async/await,或者说是生成器的 yield from。
- Event Loop,这个是 asyncio 实现的。它决定了我们能对什么事宜进行异步操作,今朝只支撑准时器与收集 IO 的异步。
推荐阅读
Android必知必会-使用Intent打开第三方应用及验证可用性
基本常识此方法多用于启动体系中的功能性应用,比如打德律风、发邮件、预览图片、应用默认浏览器打开一个网页等。1. App 的人口 Activity 与其 icon一个通俗的应用默认会有一小我口 Activ>>>详细阅读
地址:http://www.17bianji.com/lsqh/37131.html
1/2 1