作家
登录

理解Python asyncio内部实现机制

作者: 来源: 2017-09-05 08:58:59 阅读 我要评论

  •  loop = events.get_event_loop() 
  •  future = loop.create_future() 
  •  h = future._loop.call_later(delay, 
  •  futures._set_result_unless_cancelled, 
  •  future, result) 
  •  try: 
  •  return (yield from future) 
  •  finally: 
  •  h.cancel() 
    1. def __iter__(self): 
    2.  if not self.done(): 
    3.  self._asyncio_future_blocking = True 
    4.  yield self # This tells Task to wait for completion. 
    5.  assert self.done(), "yield from wasn't used with future" 
    6.  return self.result() # May raise too. 
    7.  
    8. if compat.PY35: 
    9.  __await__ = __iter__ # make compatible with 'await' expression 

    留意这里的 yield self !也就是说 future 在第一次履行到这里时,会暂停履行并返回它本身,因为 coroutine 中应用的都是 yield from/await (它们在接收的参数上有差别,但在本文的评论辩论中没有差别),是以这个值会一向向上传递,到 Task._step 函数的 result = coro.send(None) 这里,那我们来看看 Task 对 result 做了什么,重要的是 这一句 :

    1. result.add_done_callback(self._wakeup) 

    也就是说 task( print_sum ) 获得了最内层暂停的 sleep 生成的 future 并为该 future 注册了一个回调,使得在 future.set_result 被调用时, task._wakeup 会被调用。这部分的逻辑可以看 这里 。

    我们再回过火来看看 future.set_result 会在什么时刻被调用,在 asyncio.sleep 函数里,我们为 event loop 注册了一个回调函数:

    1. h = future._loop.call_later(delay, 
    2.  futures._set_result_unless_cancelled, 
    3.  future, result) 

    那么这个 _set_result_unless_cancelled 是如许的:

    1. def _set_result_unless_cancelled(fut, result): 
    2.  """Helper setting the result only if the future was not cancelled.""" 
    3.  if fut.cancelled(): 
    4.  return 
    5.  fut.set_result(result) 

    这里 poll_events 之前,会去计算所有急鹞鲼事宜起码须要等待的时光,这个时光内即使没有事宜产生, poll_events 也会退出,以便触发急鹞鲼事宜。 _process_timeout_events 函数的感化是比较当前时光与急鹞鲼的目标履行时光,如不雅目标履行时光已经达到,则履行响应的回调函数。

    是以,所有的流程应当是如许的:

    【编辑推荐】

    1. 应用Python和Asyncio编写在线多人游戏(一)
    2. 应用Python和Asyncio编写在线多人游戏(二)
    3. 应用Python和Asyncio编写在线多人游戏(三)
    4. Python 中的异步编程:Asyncio
    5. Python中的异步编程:Asyncio
    【义务编辑:未丽燕 TEL:(010)68476606】

    懂得Python asyncio内部实现机制

    小结

    那么 asyncio 做为一个库,做了什么,没做什么?

    1. 控制流的暂停与恢复,这是经由过程 Python 内部的 Generator(生成器)相干的功能实现的。
    2. 协程链,即把不合协程链链接在一路的机制。依旧是经由过程 Python 的内置支撑,即 async/await,或者说是生成器的 yield from。
    3. Event Loop,这个是 asyncio 实现的。它决定了我们能对什么事宜进行异步操作,今朝只支撑准时器与收集 IO 的异步。

    4.   推荐阅读

        Android必知必会-使用Intent打开第三方应用及验证可用性

      基本常识此方法多用于启动体系中的功能性应用,比如打德律风、发邮件、预览图片、应用默认浏览器打开一个网页等。1. App 的人口 Activity 与其 icon一个通俗的应用默认会有一小我口 Activ>>>详细阅读


      本文标题:理解Python asyncio内部实现机制

      地址:http://www.17bianji.com/lsqh/37131.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)