How to exchange values betwwen async function whic

2019-08-16 23:30发布

问题:

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)

demo code:

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

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

回答1:

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()

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)