Search code examples
pythonpython-3.xmultithreadingpython-multiprocessing

Unable to get data from parent process to child process


I am using a Python3 program to create two processes: the child born out of the parent process. Everything starts with the parent process. The motive is to start a process, give it the live sensor data, and end it when the sensor reading passes a certain threshold.

The sensor_data is obtained through a thread in the parent process as:

t = Thread(target=dump_sensor_data,args=())
t.start()

And I have tested that the live data can be used in any function as

while True:
    global sensor_data
    print(sensor_data)

The child process is defined as:

def fa():
    global sensor_data
    while sensor_data>300:
        print(f'I am printing {sensor_data} from fa')
        time.sleep(0.7)

I start it as:

processes_list=[]
pa=Process(target=fa, args=())
pa.start()
processes_list.append(pa) 

Now, I create another watch-guard function that kills the child process fa() as soon as the sensor_data exceeds 300.

def watchguard():
    global sensor_data
    while True:
        print(lidar1)
        if sensor_data > 300:
            for p in processes_list:
                print(f'terminating process {p}')
                p.terminate()
                p.join()
                return

But this is what happens

0
terminating process <Process(Process-1, started)>

The 0 is the wrong value of sensor_data which I have verified and should be above 1000. Also, this leads to the process getting killed.

Why is the data not getting passed to this child process ?


Solution

  • Ok, I got it.

    As Python multiprocessing does not allow global variables to be passed between processes, the variable was never sent or updated. This is not the case with multithreading.