The problem is that I need to create an async method/library as follow (so that it does not block asyncio event loop):
- Create future from the being defined async method (let's say it methodA)
- Put the future into some Queue/List/Dict and one service will fill result into the future when available (the result take long time to be available)
- await the future in the methodA
The problem I have is awaiting for the created future is blocking forever as simplified example below.
import asyncio from asyncio import Future from queue import Queue from threading import Thread futures_queue: Queue[Future] = Queue() def fill_result_service(): counter = 0 while True: fut = futures_queue.get() print(f"Processing fut={id(fut)}") fut.set_result(f"OK: {counter}") counter += 1 filler_thread = Thread(target=fill_result_service) filler_thread.start() async def main_not_ok(): fut: Future[str] = asyncio.get_running_loop().create_future() print(f"Putting fut={id(fut)} into queue") futures_queue.put(fut) result = await fut assert result.startswith("OK") print("main_not_ok() completed") async def main_ok(): fut: Future[str] = asyncio.get_running_loop().create_future() tmp_thread = Thread(target=lambda: fut.set_result("OK: Local thread")) tmp_thread.start() result = await fut assert result.startswith("OK") print("main_ok() completed") if __name__ == "__main__": print("Running main_ok: ") asyncio.run(main_ok()) # work as expected print("\n\n\nRunning main_not_ok: ") asyncio.run(main_not_ok()) #blocking forever I have struggled to debug it for half-day and can't figure it out. Please help me.