gpt4 book ai didi

python - 多处理中的管理器字典

转载 作者:IT老高 更新时间:2023-10-28 20:37:16 26 4
gpt4 key购买 nike

这是一个简单的多处理代码:

from multiprocessing import Process, Manager

manager = Manager()
d = manager.dict()

def f():
d[1].append(4)
print d

if __name__ == '__main__':
d[1] = []
p = Process(target=f)
p.start()
p.join()

我得到的输出是:

{1: []}

为什么我没有得到 {1: [4]} 作为输出?

最佳答案

这是你写的:

# from here code executes in main process and all child processes
# every process makes all these imports
from multiprocessing import Process, Manager

# every process creates own 'manager' and 'd'
manager = Manager()
# BTW, Manager is also child process, and
# in its initialization it creates new Manager, and new Manager
# creates new and new and new
# Did you checked how many python processes were in your system? - a lot!
d = manager.dict()

def f():
# 'd' - is that 'd', that is defined in globals in this, current process
d[1].append(4)
print d

if __name__ == '__main__':
# from here code executes ONLY in main process
d[1] = []
p = Process(target=f)
p.start()
p.join()

这是你应该写的:

from multiprocessing import Process, Manager
def f(d):
d[1] = d[1] + [4]
print d

if __name__ == '__main__':
manager = Manager() # create only 1 mgr
d = manager.dict() # create only 1 dict
d[1] = []
p = Process(target=f,args=(d,)) # say to 'f', in which 'd' it should append
p.start()
p.join()

关于python - 多处理中的管理器字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8640367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com