内部asyncio.sleep()
返回Future
对象。 未来的值将在超时过期后设置。
每个协同程序由asyncio.Task
执行。未来冒出来的任务亚军(实际上是Task._step()
)。 奔跑者增加了一个回调来冒泡未来在将来完成时醒来。
sleep()
实现很简单:
@coroutine
def sleep(delay, result=None, *, loop=None):
"""Coroutine that completes after a given time (in seconds)."""
if delay == 0:
yield
return result
if loop is None:
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()
任务运行是兽要复杂得多,但它的源代码仍然可读:https://github.com/python/asyncio/blob/master/asyncio/tasks.py#L223-L300
每阻塞IO太(也许从很深的内部调用返回一个未来)。当IO等待完成时,给定的值(或例外)被分配给将来,任务运行器被唤醒并且暂停协程被恢复。
是的!修正了,谢谢。 – Paul