与协程(asyncio中的状态机)进行双向通信

时间:2018-08-14 22:15:11

标签: python-3.x python-asyncio

使用sendyield,我们可以与生成器进行双向通信,并很好地实现状态机(请参见下面的示例)。现在,我们无法(?)发送到异步协程,那么如何使用异步协程实现状态机呢?

发电机示例

def lock():
    combination = [1, 2, 3]
    for digit in combination:
        a = (yield True)
        while a != digit:
            a = (yield False)

    yield "You're in"


def main():
    l = lock()
    next(l)
    assert l.send(2) == False
    assert l.send(1) == True  # correct value 1st digit
    assert l.send(1) == False
    assert l.send(2) == True  # correct value 2nd digit
    assert l.send(2) == False
    assert l.send(3) == "You're in"  # correct value 3rd digit

与asyncio相似的东西不是那么好。是否有更好的方法?

异步建议

import asyncio


class AsyncLock:
    class Message:
        def __init__(self, value):
            self.f = asyncio.Future()
            self.value = value

        def set_result(self, v):
            self.f.set_result(v)

        async def result(self):
            return await self.f

    def __init__(self, msg_q):
        self.msg_q = msg_q
        self.task = None

    async def send(self, value):
        msg = AsyncLock.Message(value)
        await self.msg_q.put(msg)
        return await msg.result()

    # all of the above to be able to do this:
    async def run(self):
        combination = [1, 2, 3]
        for digit in combination:
            msg = await self.msg_q.get()
            while msg.value != digit:
                msg.set_result(False)
                msg = await self.msg_q.get()
            msg.set_result("You're in" if digit == 3 else True)


async def amain():
    l = AsyncLock(asyncio.Queue())
    l.task = asyncio.ensure_future(l.run())

    assert await l.send(2) == False
    assert await l.send(1) == True
    assert await l.send(1) == False
    assert await l.send(2) == True
    assert await l.send(2) == False
    assert await l.send(3) == "You're in"

asyncio.get_event_loop().run_until_complete(amain())

1 个答案:

答案 0 :(得分:1)

Python3.6添加了对异步生成器(PEP525)的支持,因此async函数现在也可以成为生成器!

#!/usr/bin/env python3.6

import asyncio

async def lock():
    combination = [1, 2, 3]
    for digit in combination:
        a = (yield True)
        while a != digit:
            a = (yield False)
    yield "You're in!"

async def main():
    coro = lock()
    await coro.asend(None)
    assert (await coro.asend(2)) == False
    assert (await coro.asend(1)) == True
    assert (await coro.asend(1)) == False
    assert (await coro.asend(2)) == True
    assert (await coro.asend(2)) == False
    assert (await coro.asend(3)) == "You're in!"
    print('Got it')

iol = asyncio.get_event_loop()
iol.run_until_complete(main())

在Python3.6之前,最好的方法是像以前一样使用消息队列。