如何在python3.5中永远运行的异步函数之间交换值? [英] How to exchange values betwwen async function which are running forever in python3.5?

查看:20
本文介绍了如何在python3.5中永远运行的异步函数之间交换值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to learn python async module, and I have searched everywhere on the Internet including youtube pycon and various other videos, but i could not find a way to get variables from one async function (running forever) and to pass variable to other async function (running forever)

演示代码:

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

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

推荐答案

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

As with any other Python code, the two coroutines can communicate using an object they both share, most typically 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() 快,在这种情况下,它会多次看到相同的值.这两个问题的解决方案是通过有界队列进行通信:

The issue with the above code is that one() keeps producing values regardless of whether anyone is reading them. Also, there is no guarantee that two() is not running faster than one(), in which case it will see the same value more than once. The solution to both problems is to communicate via a bounded queue:

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)

这篇关于如何在python3.5中永远运行的异步函数之间交换值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆