为什么使用 create_task 运行 永远创建期货?
Why do futures created using create_task run forever?
所以,我正在摆弄 Python 的 asyncio
,我正在使用 loop.create_task(myfunct())
创建新的期货。当 myfunct()
完成时,它 returns。由于我使用 loop.run_until_complete(..)
创建了循环,因此我希望 create_task
创建的线程在函数完成后将被销毁。但是当我在 Process Explorer 中观察 Python 进程时,我发现线程永远不会被破坏。
进程启动时的线程数:7
一些工作完成后的线程数:25
这里出了什么问题?
import sys
import asyncio
async def async_process_line(line):
print("STARTED WORKING LINE\t'" + line + "'")
await asyncio.sleep(3)
return line
# Optional callback function
def write_stdout(future):
print("FINISHED WORKING LINE\t'" + future.result() + "'")
async def async_read_stdin(loop):
while True:
line = await loop.run_in_executor(None, sys.stdin.readline)
line = str(line).strip()
# Exit loop when "exit" is typed in stdin
if(line == "exit"):
break
elif(line != ""):
task = loop.create_task(async_process_line(line))
# optional callback binding
task.add_done_callback(write_stdout)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(async_read_stdin(loop))
except KeyboardInterrupt:
pass
finally:
loop.close()
你说
I'd expect that a thread created by create_task
will be destroyed once it's function finished
但 create_task
根本不创建线程。您看到的线程与 create_task
完全无关。这里没有任何问题。
您看到的大多数线程来自用作 run_in_executor
的默认执行程序的 ThreadPoolExecutor
。
所以,我正在摆弄 Python 的 asyncio
,我正在使用 loop.create_task(myfunct())
创建新的期货。当 myfunct()
完成时,它 returns。由于我使用 loop.run_until_complete(..)
创建了循环,因此我希望 create_task
创建的线程在函数完成后将被销毁。但是当我在 Process Explorer 中观察 Python 进程时,我发现线程永远不会被破坏。
进程启动时的线程数:7
一些工作完成后的线程数:25
这里出了什么问题?
import sys
import asyncio
async def async_process_line(line):
print("STARTED WORKING LINE\t'" + line + "'")
await asyncio.sleep(3)
return line
# Optional callback function
def write_stdout(future):
print("FINISHED WORKING LINE\t'" + future.result() + "'")
async def async_read_stdin(loop):
while True:
line = await loop.run_in_executor(None, sys.stdin.readline)
line = str(line).strip()
# Exit loop when "exit" is typed in stdin
if(line == "exit"):
break
elif(line != ""):
task = loop.create_task(async_process_line(line))
# optional callback binding
task.add_done_callback(write_stdout)
if __name__ == "__main__":
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(async_read_stdin(loop))
except KeyboardInterrupt:
pass
finally:
loop.close()
你说
I'd expect that a thread created by
create_task
will be destroyed once it's function finished
但 create_task
根本不创建线程。您看到的线程与 create_task
完全无关。这里没有任何问题。
您看到的大多数线程来自用作 run_in_executor
的默认执行程序的 ThreadPoolExecutor
。