4

Hello I would like to know. How Can I wait asyncio.Future from another thread and another loop? For example. I have a code that wait result from coroutine

 if isinstance(target, Future): await target result = target 

but the problem is that this code is running from another thread. And I get a exception

got Future attached to a different loop

Question: How Can I wait asyncio.Future from another thread?

P.S. I understand that I must use one Loop but architecture of my solution required to start a separate thread and wait for completion asyncio.Future

1
  • 1
    I understand that you sometimes need two threads, but why do you need two separate loops? If you start a separate thread, you can still submit stuff to the original loop. Commented Sep 6, 2019 at 13:30

1 Answer 1

3

How Can I wait asyncio.Future from another thread and another loop?

You're not supposed to. Even if you need another thread, you can always submit work to an existing single event loop using asyncio.run_coroutine_threadsafe.

But if you really really need this, you can do it like this (untested), although I would strongly advise against it. This will temporarily work around serious architectural issues, which will come back to haunt you.

if isinstance(target, Future): my_loop = asyncio.get_running_loop() if target.get_loop() is my_loop: result = await target else: target_loop = target.get_loop() my_target = my_loop.create_future() def wait_target(): try: result = await target except Exception as e: my_loop.call_soon_threadsafe(my_target.set_exception, e) else: my_loop.call_soon_threadsafe(my_target.set_result, result) target_loop.call_soon_threadsafe(wait_target) result = await my_target 
Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, this has a tendency to haunt you. I had an API with a loop spawned in each thread, and I had bugs associated with something similar to this. The best alternative was to use an event-loop based API to mitigate the issue - just if anyone wanted to know just how much this haunts.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.