我无法理解Python 3.7中引入的asyncio.create_task()
函数应该如何工作。如果我这样做:
import asyncio
async def helloworld():
print("Hello world from a coroutine!")
asyncio.create_task(helloworld())
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(helloworld())
if __name__ == "__main__":
main()
我得到:
Hello world from a coroutine!
Hello world from a coroutine!
作为输出(即协程运行两次)。但这怎么不是无限递归呢?我期望看到使用await
关键字时看到的内容:
import asyncio
async def helloworld():
print("Hello world from a coroutine!")
await helloworld()
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(helloworld())
if __name__ == "__main__":
main()
有了这个我得到:
Hello world from a coroutine!
Hello world from a coroutine!
Hello world from a coroutine!
... many more lines...
Traceback (most recent call last):
File "test3.py", line 53, in <module>
main()
File "test3.py", line 48, in main
loop.run_until_complete(helloworld())
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/base_events.py", line 568, in run_until_complete
return future.result()
File "test3.py", line 37, in helloworld
await helloworld()
File "test3.py", line 37, in helloworld
await helloworld()
File "test3.py", line 37, in helloworld
await helloworld()
[Previous line repeated 984 more times]
File "test3.py", line 36, in helloworld
print("Hello world from a coroutine!")
RecursionError: maximum recursion depth exceeded while calling a Python object
create_task
只能被安排一次,您可能会使用它的用例是什么(因为它必须在事件循环已经运行的上下文中运行)?
答案 0 :(得分:4)
任务没有被安排一次,但是循环仅在helloworld
完成之前运行。您会看到消息打印两次,因为循环使下一个任务得以运行。之后,由于循环不再运行,任务停止运行。
如果您更改
loop.run_until_complete(helloworld())
到
loop.create_task(helloworld())
loop.run_forever()
您会看到Hello world from a coroutine!
反复打印出来。
答案 1 :(得分:0)
您可以将asyncio.create_task
视为多线程世界中的守护程序线程。当“主”协程停止时,循环停止。因此,其他守护程序线程无论如何都将退出。