异步共享队列中的变量

时间:2020-06-22 11:25:46

标签: python python-asyncio

我正在研究Asyncio,到目前为止,我已经设法为所需的结构做好准备。

import asyncio
import random

async def speed_forever():
    while True:
        speed = random.randint(1,100)
        print("Speed mesuring ......", speed)
        await asyncio.sleep(1)

async def rain_forever():
    while True:
        rain = random.random()
        print("Rain mesuring .......", rain)
        await asyncio.sleep(0.1)


async def main():
    asyncio.ensure_future(speed_forever())  # fire and forget
    asyncio.ensure_future(rain_forever())  # fire and forget

    while True:
        print("*" * 40)
        print("Sending Data.....")    #Here I'd like to get access to rain and speed variable by using a queue
        print("*" * 40)
        await asyncio.sleep(5)
     

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


现在,我想从main()获得雨水和速度,因此可以对这些变量进行某些操作(例如,通过空中发送)。

  1. 由于队列失败,应如何实施?
  2. 代码结构是否足以开始使用实际代码实现功能?

1 个答案:

答案 0 :(得分:0)

这是一个框架,用于通过两个队列将数据从*_forever函数传递回main。我已经用“ ***”标记了新代码

import asyncio
import random

rain_q = asyncio.Queue()      # ***
speed_q = asyncio.Queue()     # ***

async def speed_forever():
    while True:
        speed = random.randint(1,100)
        print("Speed mesuring ......", speed)
        await speed_q.put(speed)                 # ***
        await asyncio.sleep(1)

async def rain_forever():
    while True:
        rain = random.random()
        print("Rain mesuring .......", rain)
        await rain_q.put(rain)                   # ***
        await asyncio.sleep(0.1)


async def main():
    asyncio.ensure_future(speed_forever())  # fire and forget
    asyncio.ensure_future(rain_forever())  # fire and forget

    rain = None       # *** 
    speed = None      # ***
    while True:
        print("*" * 40)

        # *** Read stuff from the queues. Here, I'm just using the latest
        # item in the queue - but one can do other things as well. 
        while not rain_q.empty(): 
            rain = await rain_q.get()
        
        while not speed_q.empty(): 
            speed = await speed_q.get()

        print(f"*** Last rain was {rain}")            
        print(f"*** Last speed was {speed}")
        print("Sending Data.....")    #Here I'd like to get access to rain and speed variable by using a queue
        print("*" * 40)
        await asyncio.sleep(5)

     

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

请注意,如果您只对队列中的最后一项感兴趣,则可以通过其他方法来实现。例如,一个将是带有最新数字的float类型的全局变量。在这种情况下,我认为这不是正确的方法。

相关问题