Search code examples
pythonfunctionloopsprocessmultiprocessing

Stop process from another process


Hi guys I have two different processes running at the same time. I'm trying to stop the other process which i have named loop_b but I have only managed to stop the current process and the other doesn't stop

from multiprocessing import Process
import time
import sys 


counter=0

def loop_a():
    global counter
    while True:
        print("a")
        time.sleep(1)
        counter+=1
        if counter==10:
            print("I want to stop the loop_b")
            sys.exit()
            #Process(target=loop_b).close()  -> Also i tried this but not worked

def loop_b():
    while True:
        print("b")
        time.sleep(1)

if __name__ == '__main__':
    Process(target=loop_a).start()
    Process(target=loop_b).start()


Solution

  • One possible solution could be using multiprocessing.Event synchronization primitive to signal other process that it should exit, e.g.:

    import sys
    import time
    from multiprocessing import Event, Process
    
    
    def loop_a(evt):
        counter = 0
    
        while True:
            print("a")
            time.sleep(1)
            counter += 1
            if counter == 3:
                print("I want to stop the loop_b")
                evt.set()  # <-- set the flag to be True to signal exit
                sys.exit()
    
    
    def loop_b(evt):
        while not evt.is_set():
            print("b")
            time.sleep(1)
    
    
    if __name__ == "__main__":
        evt = Event()
    
        p1 = Process(target=loop_a, args=(evt,)).start()
        p2 = Process(target=loop_b, args=(evt,)).start()
    

    Prints:

    a
    b
    a
    b
    a
    b
    I want to stop the loop_b  # <-- and the loob_b ends here too