A pretty simple question that I haven't been able to find an answer to:
If I want to run an asyncio event loop in its own thread, and have it send messages back to the main thread, can it do so using a queue.Queue instance?
If this is indeed possible and safe, is there a better way of passing messages from an asyncio loop in a non-main thread, to the main thread?
Here's a toy example, which seems to work:
import asyncio
from queue import Queue
import threading
queue_to_main = Queue()
async def coro1():
for i in range(5):
queue_to_main.put_nowait(i)
await asyncio.sleep(1)
queue_to_main.put_nowait("STOP")
def runloop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(coro1())
finally:
loop.close()
t1 = threading.Thread(target=runloop)
t1.start()
while True:
item = queue_to_main.get()
if item == "STOP":
break
print(item)
t1.join()
The scenario I'm envisaging is running an aiohttp server in its own thread, but letting in communicate back to the main thread as a result of certain requests.
asyncio.Queue? - dirnasyncio.Queueinstance in the main thread, sinceasyncio.Queueisn't threadsafe? I guess you might have to do something like:item = asyncio.run_coroutine_threadsafe(my_aio_queue.get(), loop).result()? - samfrances