【发布时间】:2015-08-08 02:00:51
【问题描述】:
如果我在 python3 解释器上运行它:
import asyncio
@asyncio.coroutine
def wait(n):
asyncio.sleep(n)
loop = asyncio.get_event_loop()
fut = asyncio.async(wait(10))
fut.add_done_callback(lambda x: print('Done'))
asyncio.Task.all_tasks()
我得到以下结果:
{<Task pending coro=<coro() running at /usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/asyncio/coroutines.py:139> cb=[<lambda>() at <ipython-input-5-c72c2da2ffa4>:1]>}
现在,如果我运行 fut.cancel(),我会返回 True。但是输入 fut 会返回任务的表示,说明它正在取消:
<Task cancelling coro=<coro() running at /usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/lib/python3.4/asyncio/coroutines.py:139> cb=[<lambda>() at <ipython-input-5-c72c2da2ffa4>:1]>
而且任务实际上永远不会取消(fut.cancelled() 永远不会返回 True)
为什么不取消?
【问题讨论】:
-
你可能实际上想要
yield from asyncio.sleep(n)在wait中。否则,wait将退出而不实际休眠n秒。
标签: python python-3.x concurrency python-asyncio