[英]How to Update values (List forms) from while loop in dictionary python
[英]How to update a dictionary in a while loop?
我正在使用两个循环,无法弄清楚如何在一个循环中正确更新字典并在另一个循环中使用它。
在第一个循环中,我在字典中添加了一个新对,但在第二个循环中我没有看到任何变化,我该如何正确地做到这一点?
import time
from multiprocessing import Process
dict_1 = {1:'1'}
def func_1():
while True:
dict_1.update({2:'2'})
print('Result func_1-',dict_1)
time.sleep(5)
def func_2():
while True:
print('Result func_2-',dict_1)
time.sleep(5)
if __name__ == '__main__':
p1 = Process(target=func_1)
p2 = Process(target=func_2)
p1.start()
p2.start()
p1.join()
p2.join()
Result func_1- {1: '1', 2: '2'} Result func_2- {1: '1'}
在第一个周期中,我看到了一对新的,但在第二个周期中我没有看到它。
您可以通过使用multiprocessing.Manager
为您的目的创建托管字典来解决此问题:
import time
from multiprocessing import Process, Manager
manager = Manager()
dict_1 = manager.dict({1:'1'})
def func_1():
while True:
dict_1.update({2:'2'})
print('Result func_1-',dict_1)
time.sleep(5)
def func_2():
while True:
print('Result func_2-',dict_1)
time.sleep(5)
if __name__ == '__main__':
p1 = Process(target=func_1)
p2 = Process(target=func_2)
p1.start()
p2.start()
p1.join()
p2.join()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.