【发布时间】:2018-10-10 10:05:28
【问题描述】:
我正在尝试理解 pythons asynico 模块,并在 https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task 遇到以下代码
import time
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
print('started at', time.strftime('%X'))
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print('finished at', time.strftime('%X'))
asyncio.run(main())
事实证明,await task2(或task1,但不能同时删除)可以简单地删除,并且代码看起来完全一样。我觉得这很违反直觉,这里发生了什么?
感谢您的宝贵时间。
【问题讨论】:
-
@BradSolomon,很有趣,但对我来说,如果
await task2被注释掉,两个任务都会运行,我不会得到任何取消。我在 Windows 上使用 python 3.7 -
我很困惑,一个
await可以导致两个任务都运行。
标签: python asynchronous