Search code examples
pythonmultithreadingprocess

Get periodic updates from a process


I have a function which will increment a number with time. This is given to a process; but it doesn't increment while the process runs. I want the incremented value of my global variable at regular intervals. But, I am not seeing the increment happening.

Here is what I tried:

from multiprocessing import Process
from time import sleep

x = 0;

def increment():
  global x;
  while(1):
    x +=1
    sleep(1)


process_1 = Process(target=increment)
process_1.start()

for i in range(0,10):
  print(x);
  sleep(2)

I am expecting that it will print

1
3
5
7 ...

However, it remains at 0.

What am I missing here?


Solution

  • Note that each process is a separate object(). You should pass the vars in the process, to be locally saved in the memory.

    from multiprocessing import Process, Value
    from time import sleep
    
    
    def increment(x):
        while True:
            x.value += 1
            sleep(1)
    
    
    if __name__ == '__main__':
        x = Value('i', 1)
        process_1 = Process(target=increment, args=(x,))
        process_1.start()
    
        for i in range(10):
            print(f'{i}: {x.value}')
            sleep(2)
    
    

    Prints

    0: 1
    1: 3
    2: 5
    3: 7
    4: 9
    5: 11
    6: 13
    7: 15
    8: 17
    9: 19