Inspired from the tutorial multiprocessing factorial, I have tried to multiprocess a trivial force calculation module. My main concern is the queue.get feature is not retrieving in the same order as expected. for example, instead of giving [5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5], it gives jumbled output based on different processor. 1) How can I append the results from the queue based on the process calling sequence? Should I use pool, map, lock or any such thing? 2)How can I avoid memory sync/overwriting issues?
def mp_worker(istart, iend, x, out_q1, out_q2):
global_N = len(x)
outdict1 = []
outdict2 = []
k = 0
for i in range(istart,iend,1):
temp_FX = 0
temp_FY = 0
for j in range(global_N):
if i != j:
temp_FX = temp_FX + (x[j]-x[i])
temp_FY = temp_FY + (x[j]-x[i])
outdict1.append(temp_FX)
outdict2.append(temp_FY)
k = k + 1
out_q1.put(outdict1)
out_q2.put(outdict2)
def mp_factorizer( nprocs):
x = mem.x
FORCE = mem.FORCE
N = len(FORCE)
out_q1 = multiprocessing.Queue()
out_q2 = multiprocessing.Queue()
chunksize = int(math.ceil(N / float(nprocs)))
procs = []
for i in range(nprocs):
istart = chunksize * i
iend = chunksize * (i + 1)
p = multiprocessing.Process(
target=mp_worker,
args=(istart, iend, x, out_q1, out_q2))
procs.append(p)
p.start()
# Collect all results into a single result dict. We know how many dicts
# with results to expect.
resultdict1 = []
resultdict2 = []
for i in range(nprocs):
resultdict1 = resultdict1 + out_q1.get()
resultdict2 = resultdict2 + out_q2.get()
# Wait for all worker processes to finish
for p in procs:
p.join()
return resultdict1