user45245
user45245

Reputation: 905

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

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

Upvotes: 4

Views: 2180

Answers (1)

user4815162342
user4815162342

Reputation: 154846

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

Upvotes: 3

Related Questions