gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:14 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com