Issue
is it a good idea to run the asyncio eventloop inside a thread?
import asyncio
import time
from sample_threading import parallel
loop = asyncio.new_event_loop()
async def fn(p):
for i in range(5):
print(i)
time.sleep(5)
print("done")
@parallel
def th(p):
loop.run_until_complete(fn(p))
th(1)
th(2)
th(3)
above code giving error
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
any suggestion ?
Solution
error
message you are haveing, This event loop is already running,
is beacuse when you attempt to run an asyncio
event loop that is already running. In your code, you are creating a new event loop using asyncio.new_event_loop()
, but you are not explicitly setting it as the current event loop.
import asyncio
import time
from sample_threading import parallel
async def fn(p):
for i in range(5):
print(i)
# instead of time.sleep, you ensure that the sleep operation is non-
# blocking and allows other tasks to run concurrently.
await asyncio.sleep(5)
print("done")
@parallel
def th(p):
asyncio.run(fn(p))
th(1)
th(2)
th(3)
Running the asyncio
event loop inside a thread
can be a valid approach in certain scenarios, especially when you need to perform asynchronous tasks concurrently with other operations.
Answered By - Sauron
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.