'Changed value of global variable is not used when function is called using multiprocessing in Python
I am trying to make use of a global variable which is updated in func1() and then used in func2().
When I call func2() simply without multiprocessing, it utilizes the updated value of the global variable. However, when func2() is invoked using multiprocessing it uses the old value of the global variable.
How can I make use of the updated value of the global variable while multiprocessing?
Given below is the simple code to demonstrate this:
import multiprocessing
from multiprocessing import Process
myGlobal = None
def func1():
global myGlobal
myGlobal = 42
def func2():
print(myGlobal)
if __name__ == "__main__":
print("before update")
func2()
func1()
print("after update")
func2()
print("Using multiprocessing")
list_process = []
for i in range(2):
p = Process(target=func2)
list_process.append(p)
p.start()
for i in range(2):
list_process[i].join()
Output on console:
before update
None
after update
42
Using multiprocessing
None
None
Process finished with exit code 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
