1
votes

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.

1
Do you specifically want to avoid using asyncio.Queue? - dirn
Not particularly - I would be happy to use it if that ends up being the best way of doing things in this sort of scenario. However, I guess there would be some complications getting an item from an asyncio.Queue instance in the main thread, since asyncio.Queue isn't threadsafe? I guess you might have to do something like: item = asyncio.run_coroutine_threadsafe(my_aio_queue.get(), loop).result()? - samfrances
Related: janus - Vincent

1 Answers

0
votes

asyncio.Queue is intended for usage inside the single event loop. The queue is not inter-loop communication primitive.

Moreover, you should not start several parallel loops, each in own thread. It is antipattern (at least for Python).