Search code examples
pythonmultiprocessingpython-multiprocessing

How to dynamically change the value of variable in functions while using multiprocessing


how can i dynamically change the value of lis so that every second it'll output a list in which the last element is 2x the last element of the previous list .

import time, multiprocessing

lis = [1, 2, 4]

def printer():
    while True:
        print(lis)
        time.sleep(1)

def updater():
    while True:
        time.sleep(1)
        lis.append(lis[-1]*2)

if __name__ == '__main__':
    process1 = multiprocessing.Process(target=updater)
    process2 = multiprocessing.Process(target=printer)

    process1.start()
    process2.start()

    process1.join()
    process2.join()

i need the output to be something like this

[1, 2, 4]
[1, 2, 4, 8]
[1, 2, 4. 8. 16]
[1, 2, 4, 8, 16, 32] 
.
.

but right now the output is

[1, 2, 4]
[1, 2, 4]
[1, 2, 4]
[1, 2, 4] 
.
.

I tried using global lis but that didnt work either.


Solution

  • You can achieve desired behavior using multiprocessing.Manager.

    Managers provide a way to create data which can be shared between different processes. You can read more about it here.

    Based on example from Server process section you can rewrite your code like this:

    import time, multiprocessing
    
    
    def printer(_lis):
        while True:
            print(_lis)
            time.sleep(1)
    
    def updater(_lis):
        while True:
            time.sleep(1)
            _lis.append(_lis[-1]*2)
    
    if __name__ == '__main__':
        with multiprocessing.Manager() as manager:
            lis = manager.list([1, 2, 4])
            process1 = multiprocessing.Process(target=updater, args=(lis,))
            process2 = multiprocessing.Process(target=printer, args=(lis,))
    
            process1.start()
            process2.start()
    
            process1.join()
            process2.join()