Search code examples
pythonprocess

python update variable in loop and use it in another process


Why while loop is ignored in work1? I would like to update value from string to another value in loop and output this value in process work2. Also already tried with Queue, but problem is I have only one variable which I would like to update in work1 and access to it at work2.

from multiprocessing import Process, Manager, Value
from ctypes import c_char_p
import time

def work1(string):
    i = 2

    string.value = i
    # while True:
        # print("work1")
        # string.value = i + 1
        # time.sleep(2)

def work2(string):
    while True:
        print("Value set in work1 " + str(string.value))
        time.sleep(2)

if __name__ == '__main__':
    manager = Manager()
    string = manager.Value(int, 0);

    p1=Process(target=work1, args=(string,))
    p1.start()
    p1.join()

    p2=Process(target=work2, args=(string,))
    p2.start()
    p2.join()

Solution

  • That is because you didn't make your program parallel with two processes, but instead, two processes run in tandem. What you need to do is to start both process before any join. Like my modification below:

    from multiprocessing import Process, Manager, Value
    from ctypes import c_char_p
    import time
    
    def work1(string):
        i = 2
        string.value = i
        while True:
            i = i+1
            string.value = i
            print("work1 set value to " + str(string.value))
            time.sleep(2)
    
    def work2(string):
        while True:
            print("Value set in work1" + str(string.value))
            time.sleep(2)
    
    if __name__ == '__main__':
        manager = Manager()
        string = manager.Value(int, 0, lock = False)
    
        p1 = Process(target=work1, args = (string,))
        p2 = Process(target=work2, args = (string,))
        p1.start()
        p2.start()
        p2.join()
        p1.join()
    

    Indeed, if you write the code in this way, the join never happened due to the infinite while loop.