I'm playing with python's multiprocessing module and shared memory. I able to use a shared memory object with Process
, but not with Pool
. I added a callback for my Pool
, and the callback doesn't seem to be invoked, either.
from multiprocessing import Array, Pool, Process
def flip(x,a):
a[x] = 0 if a[x] else 1
return (x, a[x])
def cb(result):
print(result)
if __name__ == '__main__':
# size of array
N = 10
# shared array - N bytes - unsynchronized - initialized to zeros
a = Array('B', N, lock=False)
# flip values to ones using Process
processes = [Process(target=flip, args=(x, a)) for x in range(N)]
for p in processes: p.start()
for p in processes: p.join()
print([a[i] for i in range(N)])
# flip values back to zeros using Pool
pool = Pool(processes=4)
for x in range(N):
pool.apply_async(flip, args=(x, a), callback=cb)
pool.close()
pool.join()
print([a[i] for i in range(N)])
I'd expect my shared array to get printed once with all 1's, followed by single lines printed by callback
and the array again with all 0's, but get this instead;
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Why isn't the Pool
running the tasks?
Taking out shared memory, for the sake of a minimal example;
def f(x):
return x
def cb(result):
print('cb',result)
if __name__ == '__main__':
pool = Pool(processes=4)
pool.apply_async(f, range(10), callback=cb)
pool.close()
pool.join()
I'd expect this to print the numbers 0 to 9 on separate lines, but it outputs nothing.
If I replace the apply_sync
call immediately above with this;
pool.apply_async(f, args=[10], callback=cb)
I get the output
cb 10
Replacing the [10]
with range(10)
, [1,2,3]
, [(1),(2),(3)]
, or ([1],[2],[3])
yields no output.