This script creates a parent process that executes a long-running task and a child process that does work in the background. When the parent process is finished, it sends a message to the child to stop, the child receives the message, it stops what it's doing, sends a message back to the parent that it's stopped, the parent receives the message, and then stops itself.
import queue, time
from multiprocessing import Queue, Process
class Parent:
def __init__(self):
self.send_signal_queue = Queue()
self.receive_signal_queue = Queue()
self.startChild()
print('Begin long-running task in parent.')
time.sleep(10)
print('End long-running task in parent.')
self.stopChild()
def startChild(self):
self.Child = Child(self.send_signal_queue, self.receive_signal_queue)
self.Child.start()
def stopChild(self):
self.send_signal_queue.put('Stop')
while True:
try:
self.receive_signal_queue.get_nowait()
break
except queue.Empty:
time.sleep(1)
self.Child.terminate()
self.Child.join()
class Child(Process):
def __init__(self, receive_signal_queue, send_signal_queue):
super(Child, self).__init__()
self.receive_signal_queue = receive_signal_queue
self.send_signal_queue = send_signal_queue
def run(self):
while True:
try:
self.receive_signal_queue.get_nowait()
break
except queue.Empty:
pass
print('Child doing work while parent is busy.')
time.sleep(1)
self.send_signal_queue.put('Stopped')
Parent()