In my python3 multiprocess program, I need a global variable COUNT
for counting. I use the Manager.Lock() to maintain global variable COUNT
to prevent conflicts when child-processes write this variable.
Following is my code implementation;
# Ubuntu 16.04 LTS, python 3.6
from multiprocessing import Pool, Lock, Manager
COUNT = 0
def f(lock,x):
global COUNT
with lock:
COUNT += x
print(COUNT,end=' ')
if __name__ == '__main__':
manager = Manager()
lock = manager.Lock()
print('Origin COUNT:',COUNT)
print('COUNT in child-process:',end=' ')
with Pool(4) as pool:
for i in [2,4,6,8,10]:
pool.apply(func=f,args=(lock,i))
pool.close()
pool.join()
print()
print('Final COUNT:',COUNT)
# result
Origin COUNT: 0
COUNT in child-process: 6 4 8 2 12
Final COUNT: 0
It is clear that:
- child processes operate on the same variable
COUNT
. - the operation on global variables
COUNT
by each child process is Not all saved.(WHY?)
Final COUNT is 0??? Shouldn't the result be 30? (sum([2,4,6,8,10])
)
This really confuses me. Lock() failed?