1

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:

  1. child processes operate on the same variable COUNT.
  2. 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?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Norman
  • 11
  • 1
  • I don’t think subprocesses can change a global variable in the main program. – mkrieger1 Dec 26 '19 at 09:05
  • @mkrieger1 You enlightened me on the issue! The parent and child processes must have different namespaces. Thanks! By the way, do you have any suggestions for this implementation? – Norman Dec 26 '19 at 09:17

0 Answers0