# 代码片段1
#一个协程执行流程被打断的最主要的原因就是在协程内部调用了另一个协程函数
import asyncio
import asyncio.coroutines
def _set_result_unless_cancelled(fut, result):
if fut.cancelled():
return
print("this is a rewrited sleep callback function")
fut.set_result(result)
# asyncio.sleep()函数的实现版本
@asyncio.coroutine
def dalong_sleep(delay, result=None, *, loop=None):
"""Coroutine that completes after a given time (in seconds)."""
#如果delay=0, 直接yield
if delay == 0:
yield
return result
future = loop.create_future()
h = future._loop.call_later(delay,
_set_result_unless_cancelled,
future, result)
try:
# 遇到yield from,则当前协程的执行流程被打断
return (yield from future)
finally:
h.cancel()
async def cor1():
# 遇到await,当前协程执行流程被打断,当前Task的唤醒函数被设置为dalong_sleep的Task的
# 的回调函数
await
2021-08-25 py协程
最新推荐文章于 2023-05-12 15:26:09 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)