Home > Mobile >  How to stop all processes if one of them changes a global "stop" variable to True
How to stop all processes if one of them changes a global "stop" variable to True

Time:12-29

import multiprocessing


global stop
stop = False


def makeprocesses():
    processes = []
    for _ in range(50):
        p = multiprocessing.Process(target=runprocess)
        
        processes.append(p)
    
    for _ in range(50):
        processes[_].start()
    runprocess()


def runprocess():
    global stop
    while stop == False:
        
        x = 1 #do something here

        if x = 1:
            stop = True




makeprocesses()

while stop == True:
    x = 0
    makeprocesses()

How could I make all the other 49 processes stop if just one changes stop to True? I would think since stop is a global variable once one process changes stop all the others would stop.

CodePudding user response:

No. Each process gets its own copy. It's global to the script, but not across processes. Remember that each process has a completely separate address space. It gets a COPY of the first process' data.

If you need to communicate across processes, you need to use one of the synchronization techniques in the multiprocessing documentation (https://docs.python.org/3/library/multiprocessing.html#synchronization-primitives), like an Event or a shared object.

CodePudding user response:

Whenever you want to synchronise threads you need some shared context and make sure it is safe. as @Tim Roberts mentioned These can be taken from (https://docs.python.org/3/library/multiprocessing.html#synchronization-primitives)

Try something like this:

import multiprocessing
from multiprocessing import Event
from time import sleep


def makeprocesses():
    processes = []
    e = Event()

    for i in range(50):
        p = multiprocessing.Process(target=runprocess,args= (e,i))
        p.start()
        processes.append(p)

    for p in processes:
        p.join()


def runprocess(e: Event() = None,name = 0):
   while not e.is_set():
        sleep(1)
        if name == 1:
            e.set()  # here we make all other processes to stop
   print("end")


if __name__ == '__main__':
    makeprocesses()

My favorite way is using cancelation token which is a object wrapping what we did here

  • Related