[英]python asyncio run infinite loop in background and access class variable from the loop
我有一個Sensor
類,它有一個數值num
。 它有一個async
方法update
,它在無限循環中每秒更新num
。
我想啟動該類並調用方法update
,使其保持運行並在一段時間后將控制權返回給主程序以訪問num
的值。 我正在使用asyncio
但不知道如何調用該方法以使循環和變量訪問的並發運行是可行的。
代碼:
import asyncio
import time
class Sensor:
def __init__(self, start=0):
self.num = start
async def update(self):
print(f"Starting Updates{self.num}")
while True:
self.num += 1
print(self.num)
await asyncio.sleep(1)
if __name__ == "__main__":
print("Main")
sensor = Sensor()
# asyncio.run(sensor.update())
# asyncio.ensure_future(sensor.update())
future = asyncio.run_coroutine_threadsafe(sensor.update(), asyncio.new_event_loop())
print("We are back")
print(f"current value: {sensor.num}")
time.sleep(4)
print(f"current value: {sensor.num}")
這讓我在等待 4 秒之前和之后輸出0
,這意味着update
方法沒有落后。 run()
根本不返回控件。
我應該調用哪種方法在后台調用無限循環?
要使用asyncio.run_coroutine_threadsafe
,您需要在單獨的線程中實際運行事件循環。 例如:
sensor = Sensor()
loop = asyncio.new_event_loop()
threading.Thread(target=loop.run_forever).start()
future = asyncio.run_coroutine_threadsafe(sensor.update(), loop)
...
loop.call_soon_threadsafe(loop.stop)
根據並發運行任務的文檔,您應該使用gather
。 例如,您的代碼將是這樣的:
import asyncio
import time
class Sensor:
def __init__(self, start=0):
self.num = start
async def update(self):
print(f"Starting Updates{self.num}")
while True:
self.num += 1
print(self.num)
await asyncio.sleep(1)
async def print_value(sensor):
print("We are back")
print(f"current value: {sensor.num}")
await asyncio.sleep(4)
print(f"current value: {sensor.num}")
async def main():
print("Main")
sensor = Sensor()
await asyncio.gather(sensor.update(), print_value(sensor))
if __name__ == "__main__":
asyncio.run(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.