Issue
So, I'm fiddling around with Python's asyncio
and I'm creating new futures using loop.create_task(myfunct())
. When myfunct()
finishes, it returns. Since I created my loop using loop.run_until_complete(..)
I'd expect that a thread created by create_task
will be destroyed once it's function finished. But when I watch the Python process in Process Explorer I see that the threads are never destroyed.
Threads after some work was done (and finished): 25
What's going wrong here?
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()
Solution
You say
I'd expect that a thread created by
create_task
will be destroyed once it's function finished
but create_task
doesn't create threads at all. The threads you're seeing have absolutely nothing to do with create_task
. Nothing is going wrong here.
Most of the threads you're seeing come from the ThreadPoolExecutor
used as the default executor for run_in_executor
.
Answered By - user2357112 supports Monica
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.