title: Python - How can I implement a 'stoppable' thread?
body: <p>There is a solution posted <a href="https://stackoverflow.com/questions/323972/is-there-any-way-to-kill-a-thread-in-python">here</a> to create a stoppable thread.  However, I am having some problems understanding how to implement this solution.</p>
  
  <p>Using the code...</p>
  
  <pre><code>import threading
  
  class StoppableThread(threading.Thread):
      """Thread class with a stop() method. The thread itself has to check
      regularly for the stopped() condition."""
  
      def __init__(self):
          super(StoppableThread, self).__init__()
          self._stop_event = threading.Event()
  
      def stop(self):
          self._stop_event.set()
  
      def stopped(self):
          return self._stop_event.is_set()
  </code></pre>
  
  <p>How can I create a thread that runs a function that prints "Hello" to the terminal every 1 second.  After 5 seconds I use the .stop() to stop the looping function/thread.</p>
  
  <p>Again I am having troubles understanding how to implement this stopping solution, here is what I have so far.</p>
  
  <pre><code>import threading
  import time
  
  class StoppableThread(threading.Thread):
      """Thread class with a stop() method. The thread itself has to check
      regularly for the stopped() condition."""
  
      def __init__(self):
          super(StoppableThread, self).__init__()
          self._stop_event = threading.Event()
  
      def stop(self):
          self._stop_event.set()
  
      def stopped(self):
          return self._stop_event.is_set()
  
  def funct():
      while not testthread.stopped():
          time.sleep(1)
          print("Hello")
  
  testthread = StoppableThread()
  testthread.start()
  time.sleep(5)
  testthread.stop()
  </code></pre>
  
  <p>Code above creates the thread testthread which can be stopped by the testthread.stop() command.  From what I understand this is just creating an empty thread... Is there a way I can create a thread that runs funct() and the thread will end when I use .stop().  Basically I do not know how to implement the StoppableThread class to run the funct() function as a thread.</p>
  
  <p>Example of a regular threaded function...</p>
  
  <pre><code>import threading
  import time
  
  def example():
      x = 0
      while x &lt; 5:
          time.sleep(1)
          print("Hello")
          x = x + 1
  
  t = threading.Thread(target=example)
  t.start()
  t.join()
  #example of a regular threaded function.
  </code></pre>