簡體   English   中英

如何在while循環中更新字典?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM