0
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.

2 Answers2

1

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.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

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

Matan Benita
  • 196
  • 1
  • 4
  • Do I need the "p.join()"? I don't really understand what .join() does. Python Docs says "This blocks the calling thread until the thread whose join() method is called terminates" But do I want the calling thread to be blocked? – Stephen Roberts Dec 29 '21 at 05:27
  • Look here to better understand what join does https://stackoverflow.com/questions/25391025/what-exactly-is-python-multiprocessing-modules-join-method-doing You will always want to use join as it blocks the calling thread (main thread in your case) until the processes ends. If you don't do so, than the main thread will finish before the processes will finish their job. joining threads are also best to free up memory and clear the thread pool (depends on implementation ) – Matan Benita Dec 29 '21 at 23:08