我正在尝试学习python异步模块,我在互联网上到处搜索,包括youtube pycon和其他各种视频,但是我找不到从一个异步函数中获取变量(永远运行)并将变量传递给其他异步函数(永久运行)的方法。
演示代码:
async def one():
while True:
ltp += random.uniform(-1, 1)
return ltp
async def printer(ltp):
while True:
print(ltp)发布于 2018-03-09 22:05:31
与任何其他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)https://stackoverflow.com/questions/49202661
复制相似问题