Skip to main content
 首页 » 编程设计

python之我如何等待来自另一个线程和另一个循环的 asyncio.Future

2024年11月01日9lautakyan007

你好,我想知道。我如何等待另一个线程和另一个循环的 asyncio.Future?例如。我有一个等待协程结果的代码

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

但问题是这段代码是从另一个线程运行的。我得到一个异常(exception)

got Future attached to a different loop

问题:如何等待来自另一个线程的 asyncio.Future?

附言我知道我必须使用一个循环,但我的解决方案的体系结构需要启动一个单独的线程并等待完成 asyncio.Future

请您参考如下方法:

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

你不应该这样做。即使您需要另一个线程,您始终可以使用 asyncio.run_coroutine_threadsafe 将工作提交到现有的单个事件循环。 .

但是如果你真的真的需要这个,你可以这样做(未经测试),尽管我强烈建议不要这样做。这将暂时解决严重的架构问题,这些问题会再次困扰您。

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