[英]Are global variables safe with Python asyncio?
subj,或者有什么更好的方法来访问异步外部数据的当前状态?
我有 2 个异步进程 data_gen() 和 worker()。
就我而言:
import asyncio
import random
DAT = 0.0
async def data_gen():
global DAT
while True:
DAT = round(random.random() * 10, 2)
print(f'data updated to: {DAT}')
await asyncio.sleep(DAT)
async def worker():
while True:
print(f'worker has {DAT}')
await asyncio.sleep(random.random() * 3)
async def main():
await asyncio.gather(data_gen(), worker())
asyncio.run(main())
Python asyncio 的全局变量是否安全?
对,他们是; 实际上一次只有一个协程在运行,直到await
ed
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.