I am looking for the best solution for communication between async tasks and methods/functions that run in a thread pool executor from concurrent.futures. In previous synchronous projects, I would use the queue.Queue
class. I assume that any method should be thread safe and therefore the asyncio.queue
will not work.
I have seen people extend the queue.Queue
class to do something like:
class async_queue(Queue):
async def aput(self, item):
self.put_nowait(item)
async def aget(self):
resp = await asyncio.get_event_loop().run_in_executor( None, self.get )
return resp
Is there a better way?
asyncio
queues are not thread safe. They are meant to be used to communicate between coroutines. Since the coroutines all run in an event loop which runs on a single thread, this is why the lack of thread safety doesn't matter between coroutines. But it would matter with non-event loop code. – Enervate