如何在 python3.5 中永远 运行 的异步函数之间交换值?

How to exchange values betwwen async function which are running forever in python3.5?

我正在尝试学习 python 异步模块,我在互联网上到处搜索,包括 youtube pycon 和其他各种视频,但我找不到从一个异步函数获取变量的方法( 运行 永远)并将变量传递给其他异步函数(运行 永远)

演示代码:

async def one():
    while True:
        ltp += random.uniform(-1, 1)
        return ltp

async def printer(ltp):
    while True:
        print(ltp)

与任何其他 Python 代码一样,这两个协程可以使用它们共享的对象进行通信,最典型的是 self:

class Demo:
    def __init__(self):
        self.ltp = 0

    async def one(self):
        while True:
            self.ltp += random.uniform(-1, 1)
            await asyncio.sleep(0)

    async def two(self):
        while True:
            print(self.ltp)
            await asyncio.sleep(0)

loop = asyncio.get_event_loop()
d = Demo()
loop.create_task(d.one())
loop.create_task(d.two())
loop.run_forever()

上述代码的问题是 one() 一直在生成值,无论是否有人在阅读它们。此外,不能保证 two() 不会 运行 比 one() 快,在这种情况下,它会不止一次看到相同的值。这两个问题的解决方案是通过有界队列进行通信:

class Demo:
    def __init__(self):
        self.queue = asyncio.Queue(1)

    async def one(self):
        ltp = 0
        while True:
            ltp += random.uniform(-1, 1)
            await self.queue.put(ltp)

    async def two(self):
        while True:
            ltp = await self.queue.get()
            print(ltp)
            await asyncio.sleep(0)