我试图从多处理程序包中使用Pool来加快计算速度。 当我确实获得了显着的提速后,随着核心/工作人员数量的增加,我越来越缺少更多的价值。
我通过mp.value()类与所有进程共享变量。
我在哪里出错了,我该如何解决?
poss = [x+1 for x in range(20)]
all_rolls = itertools.product(poss, repeat=6)
win = mp.Value('i', 0)
draw = mp.Value('i', 0)
loose = mp.Value('i', 0)
def some_func(roll):
if(comparison on rolls):
win.value += 1
elif(other comparison):
draw.value +=1
else:
loose.value +=1
with Pool(8) as p:
p.map(some_func, all_rolls)
在16个内核上,我获得了55,923,638个值,而不是64,000,000个
答案 0 :(得分:3)
您需要使用Lock
(请参阅this article)保护对值的修改。
from multiprocessing import Lock
lock = Lock()
def some_func(roll):
with lock:
if(comparison on rolls):
win.value += 1
elif(other comparison):
draw.value +=1
else:
loose.value +=1
答案 1 :(得分:2)
除了@jfowkes回答的内容外,请注意,您还可以将每个Value与其自己的锁一起使用,这可能会使事情变得更快:
win = mp.Value('i', lock = True)
draw = mp.Value('i', lock = True)
loose = mp.Value('i', lock = True)
def some_func(roll):
if(comparison on rolls):
with win.get_lock() :
win.value += 1
elif(other comparison):
with draw.get_lock():
draw.value +=1
else:
with loose.get_lock():
loose.value +=1