0
#!/usr/bin/env python
import signal
import time
import sys
import multiprocessing

idx = 0

def worker_function():
    global idx
    idx = idx + 1
    print("idx = {0}\n".format(idx))
    time.sleep(1)


def main():
    for i in range(3):
        worker = multiprocessing.Process(target=worker_function, args=())
        worker.start()
        worker.join()


if __name__ == "__main__":
    main()

output is as follows:

idx = 1

idx = 1

idx = 1

Question> Why the python global variable cannot be updated by each individual process?

q0987
  • 34,938
  • 69
  • 242
  • 387
  • Possible duplicate of [Python multiprocessing global variable updates not returned to parent](https://stackoverflow.com/questions/11055303/python-multiprocessing-global-variable-updates-not-returned-to-parent) – How about nope Jan 17 '18 at 17:46

1 Answers1

2

Each process is updating its global variable, as you can see in the output. Else they would have shown "idx = 0". It's a complete other story if you want to share data between those processes, and obtain "idx = 1, 2, 3". See https://docs.python.org/3/library/multiprocessing.html#sharing-state-between-processes .

Gerard H. Pille
  • 2,528
  • 1
  • 13
  • 17