Python:更新paren使用的全局资源的子进程

2024-04-26 10:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在我的主应用程序中创建一个子进程,每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

我发现了很多关于多重处理的知识,但我不知道如何才能做到这一点。你知道吗


Tags: run代码childtrue应用程序字典进程def
1条回答
网友
1楼 · 发布于 2024-04-26 10:19:40

我们通常在多处理或线程中使用queue来共享数据或结果。但是,对于python,可以使用listdictManagers等构造。请在此处找到您的要求:

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

相关问题 更多 >