** 启动进程刷新Test类中的数据,而后生成一个Test类的单例,调用refresh_test_num循环查询当前Test类中的数据,发现数据并未更新。**
import time
from multiprocessing import Process
class Test:
#
def __init__(self):
self.refresh_num = 1
def refresh_num_func(self):
# 递增数据
while True:
self.refresh_num += 1
time.sleep(1)
print(f"递增函数递增中...当前刷新数为:, {self.refresh_num}")
def start(self):
threading.Thread(target=self.refresh_num_func).start()
test = Test()
def refresh_test_num():
while True:
print("查询当前递增数进行中,数值为:", test.refresh_num)
time.sleep(1)
if __name__ == '__main__':
proc_indicator_alarm_info = Process(target=test.start, ).start()
refresh_test_num()
在这里插入代码片
原因:Python进程间不支持数据共享,线程间支持。
解决方式:引用multiprocessing 中的value
import threading
import time
from multiprocessing import Process, Value
class Test:
#
def __init__(self):
pass
def refresh_num_func(self, share_value):
# 递增数据
while True:
share_value.value += 1
time.sleep(1)
print(f"递增函数递增中...当前刷新数为:, {share_value.value}")
def start(self, share_value):
threading.Thread(target=self.refresh_num_func, args=(share_value,)).start()
test = Test()
def refresh_test_num(share_value):
while True:
print("查询当前递增数进行中,数值为:", share_value.value)
time.sleep(1)
if __name__ == '__main__':
share_value = Value('i', 1)
proc_indicator_alarm_info = Process(target=test.start, args=(share_value,)).start()
refresh_test_num(share_value)
这样就能实现进程间的数据共享。