I play with python multiprocessing and shared memory. I can use the shared memory object with Process, but not with Pool. I have added a callback for mine Pool, and the callback is not called 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__':
N = 10
a = Array('B', N, lock=False)
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)])
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 expect my shared array to print once with all 1, and then single lines printed callback, and the array again with all 0, but instead we get this:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Why Poolare tasks not being performed?
Removing shared memory for 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 expect this to print numbers from 0 to 9 on separate lines, but it doesn't print anything.
If I replaced the call apply_syncdirectly above,
pool.apply_async(f, args=[10], callback=cb)
I get a conclusion
cb 10
[10] range(10), [1,2,3], [(1),(2),(3)] ([1],[2],[3]) .