gpt4 book ai didi

python 异步: Wait in coroutine for intermediate result of another coroutine

转载 作者:行者123 更新时间:2023-11-28 18:13:12 26 4
gpt4 key购买 nike

我在不同的类(class_Aclass_B)中有 2 个协程(co_Aco_B)由调度程序定期调用。在执行期间的某个时候,co_B 需要一个 co_A 在其运行期间正在计算的结果。

我想做的是这样的:

class class_A:
async def co_A(self):

# execute time consuming code

# set result that co_B needs
self.set_result(result)

# execute more time consuming code

class class_B:
async def co_B(self):

# execute time consuming code

# wait for result from co_A
result = await class_A_instance.get_result()

# execute more time consuming code

我的方法是在 class_A 中有一个空的 Future,它在 co_A 期间被填充,在 co_B 中循环等待直到 Future 被设置:

class class_A:
async def prepare(self):
self.fut = asyncio.Future()

async def co_A(self):

# execute time consuming code

# set result that co_B needs
self.fut.set_result(result)

# execute more time consuming code

class class_B:
async def co_B(self):

# execute time consuming code

# wait for result from co_A
while not class_A_instance.fut.done():
await asyncio.sleep(0)

result = class_A_instance.fut.result()

# execute more time consuming code

有没有更好的方法来执行此操作而不必在循环中休眠直到 co_A 计算出结果?

最佳答案

futures 的整体理念是您可以像等待协程、任务等一样等待它。

class class_B:   
async def co_B(self):

# execute time consuming code

# wait for result from co_A
result = await class_A_instance.fut

# execute more time consuming code

请参阅“协程可以做的事情”部分 here .

关于 python 异步: Wait in coroutine for intermediate result of another coroutine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50005974/

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