[英]How to use multiprocessing in python?
I'm trying to do a task where I would assign something to a list. 我正在尝试执行一项任务,该任务是向列表分配内容。 I'll do it with multiprocessing. 我将通过多处理来实现。 After all task is finish, I want to sum all of it. 在完成所有任务之后,我想总结所有这些。 But, What I get is not what i expected. 但是,我得到的不是我所期望的。 Do you know why do this happen? 你知道为什么会这样吗? Below is just a sample code. 下面只是一个示例代码。 The result should be 45, instead of 0. 结果应为45,而不是0。
from multiprocessing import Process
def a(b):
for i in range(10):
b[i] = i
b = [0 for _ in range(10)]
p = Process(target=a, args=(b,))
p.start()
p.join()
print sum(b)
The reason is because the list b
is mutated in a separate process. 原因是因为列表b
在单独的过程中发生了变异。 When the process gets joined, the original process knows nothing about the mutations to b
. 当进程加入时,原始进程对b
的突变一无所知。 The way to fix this is to have your list managed by a multiprocessing.Manager
. 解决此问题的方法是让列表由multiprocessing.Manager
管理。
from multiprocessing import Process,Manager
def a(b):
for i in range(10):
b[i] = i
b = [0 for _ in range(10)]
#create a manager to manage access to `b`
manager = Manager()
b = manager.list(b)
p = Process(target=a, args=(b,))
p.start()
p.join()
print sum(b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.