Search code examples
python-3.xmultiprocessing

How to know the process status in multiprocessing in the target function?


In the multiprocessing how can I know the status(like its running,killed) of current process and other process ?

My scenario is 2 process are running

process_run = multiprocessing.Process(target=run, name="run")
process_read = multiprocessing.Process(target=read_process, name="read_process")
process_run.start()
process_read.start()
processes = [process_run,process_read]

for p in processes:
    p.join()


Here I want to kill process_read once process_run execution is done.

process_read psudo code looks something like this:

def read_process():
    while True:
        #read the data and print in the terminal
        time.sleep(20)

Here I am using while True so this process will not be terminated (not a good way I know). So here I want the stopping condition like once other process is done kill this process.

Can somebody help ?


Solution

  • Use a multiprocessing.Event to signal the other process.

    Demo:

    import multiprocessing as mp
    import time
    
    def process1(stop_event):           # Each process receives the event
        while not stop_event.is_set():  # Run while event is not set
            print('process1')
            time.sleep(.1)
        print('process1: stop')
    
    def process2(stop_event):           # Each process receives the event
        for i in range(5):
            print('process2:', i)
            time.sleep(.1)
        print('process2: done')
        stop_event.set()                # Signal other process to stop
    
    if __name__ == '__main__':
        funcs = process1, process2
        stop_event = mp.Event()  # Create event and send to each process
        processes = [mp.Process(target=func, args=(stop_event,)) for func in funcs]
        for p in processes:
            p.start()
        for p in processes:
            p.join()
    

    Output:

    process1
    process2: 0
    process1
    process2: 1
    process1
    process2: 2
    process1
    process2: 3
    process1
    process2: 4
    process1
    process2: done
    process1: stop