multiprocessing
docs表示更好地继承(来自祖先进程)而不是挑选/取消分享共享资源(因此避免使用管道/队列) )。
但是,它还表示明确传递资源更好,而不是作为全球资源共享。
那么,你如何传递共享资源,例如到地图功能?
此示例显示共享全局工作(但不明确),
import multiprocessing.sharedctypes
import numpy as np
def task(i):
global x
x[i] = i
sharedresource = multiprocessing.sharedctypes.RawArray('b', 10)
x = np.frombuffer(sharedresource, dtype=np.uint8)
with multiprocessing.Pool(4) as pool:
pool.map(task, range(10)) # implicitly modify x
print(x) # [0 1 2 3 4 5 6 7 8 9]
但显式传递不起作用(可能在某些队列中腌制已破坏共享连接):
def task2(i, array):
array[i] = 7
with multiprocessing.Pool(4) as pool:
pool.starmap(task2, ((i,x) for i in range(10))) # explicit fail
print(x) # still [0 1 2 3 4 5 6 7 8 9]