title: How to stop a multiprocessing.Process
body: <p>I wish to run a few threads in a process. The main process shall tell this process when to stop. I am wondering if the following code is the nicest way to do this. In particular, I think the line <code>while not self.event.is_set(): time.sleep(1)</code> is weird but maybe its the best solution.</p>
  
  <pre><code>import threading
  import multiprocessing
  import time
  
  class T(threading.Thread):
      def __init__(self):
          super(T, self).__init__()
          self.finished = False
  
      def run(self):
          while not self.finished:
              print("*")
              time.sleep(1)
  
      def stop(self):
          self.finished = True
          if self.is_alive(): self.join()
  
  
  class P(multiprocessing.Process):
      def __init__(self):
          super(P, self).__init__()
          self.event = multiprocessing.Event() 
  
          self.t1 = T()
          self.t2 = T()
  
      def run(self):
          self.t1.start()
          self.t2.start()
          while not self.event.is_set(): time.sleep(1)
          self.t1.stop()
          self.t2.stop()  
  
      def stop(self):
          self.event.set()
          self.join() 
  
  p = P()
  try:
      p.start()
      time.sleep(3)
  finally:
      p.stop()
  </code></pre>