Reputation: 189
How to terminate both processes simultaneously? Code below starts and awaits for both processes to end execution until it terminates them, I want to terminate both processes when one of them reaches the goal first. (Enters loop 1000 times and calculates i^i)
from multiprocessing import Process
from os import _exit
def foo():
for i in range(1000):
i ** i
print('EXITED')
_exit(0)
# exit(0)
# quit()
# __import__('sys').exit(0)
if __name__ == '__main__':
p1 = Process(target=foo, daemon=True)
p2 = Process(target=foo, daemon=True)
for process in (p1, p2):
process.start()
for process in (p1, p2):
process.join()
Upvotes: 1
Views: 80
Reputation: 44013
Pass to each process a multiprocessing.Event
instance that the processes set when they complete. The main process simply waits for the event to be set indicating that a process has completed.
If the tasks are daemon tasks and the main process has nothing further to do, it can simply exit and whatever daemon processes that are running will be automatically terminated. Otherwise, the main process can explicitly terminate all processes in which case there is no need to make the subprocesses daemon processes.
def foo(event, n):
for i in range(n):
i ** i
print('EXITED, n =', n)
event.set()
if __name__ == '__main__':
from multiprocessing import Process, Event
event = Event()
# So processes end at different times:
p1 = Process(target=foo, daemon=True, args=(event, 1_000_000_000))
p2 = Process(target=foo, daemon=True, args=(event, 1_000))
for process in (p1, p2):
process.start()
# Wait for a process to complete:
event.wait()
# exiting is sufficient
"""
# If you have other processing to do, then explicitly terminate the subprocesses,
# in which case there was no need to make them daemon processes.
for process in (p1, p2):
process.terminate()
"""
Prints:
EXITED, n = 1000
Upvotes: 2