use*_*646 1 arguments python-3.x python-asyncio
我正在尝试学习 python 异步模块,我在互联网上到处搜索,包括 youtube pycon 和各种其他视频,但我找不到一种方法从一个异步函数(永远运行)获取变量并将变量传递给其他异步函数(永远运行)
演示代码:
async def one():
while True:
ltp += random.uniform(-1, 1)
return ltp
async def printer(ltp):
while True:
print(ltp)
Run Code Online (Sandbox Code Playgroud)
与任何其他 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()
Run Code Online (Sandbox Code Playgroud)
上面代码的问题在于,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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1955 次 |
| 最近记录: |