簡體   English   中英

Python:子進程更新父進程使用的全局資源

[英]Python: child process to update global resources used by parent

我需要在我的主應用程序中創建一個子進程,每 n 秒更新一個 dict。

該字典將被父進程用作全局變量。

這是我正在嘗試做的偽代碼:

dict_ = {"a":12,"b":23}


def child_process()
    global dict_
    while True:
       # update dict_
       time.sleep(n)

def parent_process():
    global dict_
    # use dict_ WITHOUT MODIFYING IT

if __name__ == '__main__':
    # 1- run child process 
    # 2- run parent process

我發現了很多關於多處理的信息,但我不知道如何做到這一點。

我們通常在多處理或線程中使用隊列來共享數據或結果。 但是,對於像listdict 管理器這樣的 python 結構,使用。 請在此處找到您的要求:

from multiprocessing import Process, Manager

dict_ = Manager().dict({"a":12,"b":23})

def child_process(_dict):
    while _dict['b'] < 30:
        _dict['b'] += 1

if __name__ == '__main__':
    proc = Process(target=child_process, args=(dict_,))
    proc.start()
    # Here output printed is value from 23 to 30.
    # while proc.is_alive():
    #     print dict_.get("b")
    proc.join()
    print dict_.get("b")    # prints 30

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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