python asyncio:在协程中等待另一个协同程序的中间结果

时间:2018-04-24 15:49:53

标签: python python-asyncio

我在调度程序定期调用的不同类(co_Aco_B)中有2个协同程序(class_Aclass_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计算结果之前,是否有更好的方法可以不必在循环中睡觉?

2 个答案:

答案 0 :(得分:1)

期货的整体理念是你可以像协程,任务等一样等待它。

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

答案 1 :(得分:0)

我会使用Event类来同步协同程序。 @Mikhail方法100%正确但未解决您希望在co_A中间收到通知。

class A:
    def __init__(self):
        self.partially_ready = asyncio.Event()

    async def prepare(self):
        self.partially_ready.clear()

    async def co_A(self):   
        # execute time consuming code

        # set result that co_B needs
        self.partially_ready.set()
        # execute more time consuming code


class class_B:   
    async def co_B(self):

        # execute time consuming code

        # wait for result from co_A
        await A_instance.partially_ready.wait()
        # here A_instance finished some part you would like to wait