Issue
Running the below code is throwing runtime error, As the event loop is still not closed from the print statement before the loop is closed explicitly
import time
import asyncio
def blocking():
time.sleep(0.5)
print(f"{time.ctime()} Hello from a thread!")
loop = asyncio.get_event_loop()
loop.run_in_executor(None, blocking)
pending = asyncio.all_tasks(loop=loop)
for task in pending:
task.cancel()
group = asyncio.gather(*pending, return_exceptions=True)
loop.run_until_complete(group)
print(asyncio.get_event_loop().is_closed()) # returns false
loop.close()
What am I missing ? (Did the main thread close the loop before the blocking function code ran?)
Solution
The loop.run_in_executor(None, blocking)
call doesn't create a task in the loop, but only returns a future, with the work being immediately submitted to the executor.
Because of this, asyncio.all_tasks
returns nothing, and even if the future was returned, you can't cancel it after it's started as it's wrapping a concurrent.futures.Future
.
As the executor is started, it does your sleep while the main thread continues and closes the loop, then after it finishes, asyncio tries to set the returned result on the Future
it returned which fails.
Answered By - Numerlor
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.