Iverie Iverie - 4 months ago 24
Python Question

Python, have a process run in the background and get status from the main thread

this is a noob question, I have never done much in Python. I need to have a main process run and do stuff, while a background process does other calculations and saves the result to a variable. When the main thread wants, it should be able to read the last value stored in the variable: every value stored before is forgotten. Say that the background process is counting: I want to know what number it is at at this very moment. Here's a dummy code:

from multiprocessing import Process, Pipe
import os
import time

def f(queue):
a=0
while True:
a=a+1
child_conn.send(a)
time.sleep(0.1)

if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
time.sleep(1)
while True:
print(parent_conn.recv())
time.sleep(1)


So the main thread prints the variable of the background thread every second, which is updated 10 times a second.
I have tried with Pipe and Queue, but I do not get the last stored variable. This output is 1,2,3,4,... while I want to get 10,20,30,... (or similar, depending on timing). The problem here is that it, as the name suggests, works as a queue.

What I would do in java is create something like an asynctask and have it update a public variable, but my understanding is that multi processes cannot share variables.

What's the proper way of doing this with Python?

Answer

Use multiprocessing.Value:

from multiprocessing import Process, Value
import os
import time

def f(n):
    while True:
        n.value += 1
        time.sleep(0.1)

if __name__ == '__main__':
    n = Value('i',0)
    p = Process(target=f, args=(n,))
    p.start()
    while True:
        time.sleep(1)
        print(n.value)

Output:

7
17
26
35
44
53
Comments