For this to work you need to have communication between the worker processes and the main process. Probably the simplest way is to use multiprocessing.Event
.
Before starting the processes, create a pair of multiprocessing.Event
. Give them meaningful names like stop_main
and stop_workers
. For portability, one should give add these Event
s to the arguments given for the Process
target.
A worker process should call stop_main.set()
when it wants the main program to exit. A worker process should also call stop_workers.is_set()
regularly and exit when this returns True
.
After the main process starts all the workers it should keep polling stop_main.is_set()
. When that returns True
it should call stop_workers.set()
, join
the workers and exit.
Updated:
Edited to make it shorter and hopefully make it work on ms-windows.
An example:
import multiprocessing as mp
import time
def worker(num, sw, sm):
if num == 5:
print('This is worker', num)
time.sleep(1)
print('Worker', num, 'signalling main program to quit')
sm.set()
while not sw.is_set():
print('This is worker', num)
time.sleep(0.7)
else:
print('Worker', num, 'signing off..')
if __name__ == '__main__':
stop_worker = mp.Event()
stop_main = mp.Event()
workers = [mp.Process(target=worker, args=(n, stop_worker, stop_main))
for n in range(1, 6)]
for w in workers:
w.start()
while not stop_main.is_set():
time.sleep(1)
print('MAIN: Received stop event')
print('MAIN: Sending stop event to workers')
stop_worker.set()
for c, w in enumerate(workers, start=1):
w.join()
print('worker', c, 'joined')
It runs like this:
This is worker 1
This is worker 2
This is worker 3
This is worker 4
This is worker 5
This is worker 2
This is worker 3
This is worker 1
This is worker 4
Worker 5 signalling main program to quit
This is worker 5
This is worker 2
This is worker 3
This is worker 1
This is worker 4
This is worker 5
MAIN: Received stop event
MAIN: Sending stop event to workers
Worker 3 signing off..
Worker 1 signing off..
Worker 2 signing off..
worker 1 joined
worker 2 joined
worker 3 joined
Worker 4 signing off..
worker 4 joined
Worker 5 signing off..
worker 5 joined