[英]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.