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

标签 python multithreading python-asyncio

你好,我想知道。我如何等待另一个线程和另一个循环的 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

关于python - 我如何等待来自另一个线程和另一个循环的 asyncio.Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57819919/

相关文章:

python - 在 Pandas 的两个单独列中返回第一个值,然后返回所有其他值

java - Android 中的线程

python - 如何从Python实时读取终端输出?

python asyncio,如何从另一个线程创建和取消任务

python-3.x - 使用 asyncio 等待子进程的结果

python - 为什么当套接字变得可读时,10 个选择过程中只有 2 个被通知?

python - 我如何获得Tkinter askopenfilename()在其他窗口顶部打开?

python - 如何在python中构建动态sql查询并使用executemany()插入?

Python 使函数始终使用线程而不调用 thread.start()

python - 异步队列消费者协程