Search code examples
pythonmultithreadingmultiprocessingpython-multiprocessing

How to access global variables from separate processes


i have two python processes running on different cores that need to communicate between each other while they are running. At the moment i can achieve this via multithreading;

import threading
x=0
def a():
    global x
    if x==100:
        pass
        #Do something

def b():
    global x
    while 1:
        x=x+1
t1=threading.thread(target=a)
t2=threading.thread(target=b)
t1.start()
t2.start()

But i would like to use the multiprocessing module instead. Is there any way to covert the above code into something using multiprocessing?


Solution

  • Here's an example like your original but using multiprocessing...

    from multiprocessing import Process, Value
    
    def a(x):
        while True:
            if x.value == 10:
                print('Done.  x = ', x.value) 
                break
    
    def b(x):
        for _ in range(10):
            x.value += 1
    
    x = Value('i', 0)   # integer with initial value of 0
    t1=Process(target=a, args=(x,))
    t2=Process(target=b, args=(x,))
    t1.start()
    t2.start()
    

    Note that while I did pass in x as a parameter to the function, it looks like this still works if you simply use it as global, as you have above. The real trick here is to use the multiprocessing.Value object and access it with x.value.