title: Setting a Variable inside a Running Thread to Stop the Thread
body: <p>I have an object <code>cooker</code> whose <code>run()</code> method starts a new thread <code>cookingThread</code>. After 5 seconds, how can I stop <code>cookingThread</code> by setting its variable <code>stopThread</code>?</p>
  
  <p>Tried using <code>cooker.toggle()</code> to first start the thread, but the next <code>cooker.toggle()</code> was not able to stop the thread.</p>
  
  <p>The following code gives me the error <code>NameError: global name 'cookingThread' is not defined</code></p>
  
  <pre><code>import threading
  import time
  
  class Cooker(object):
  
      def __init__(self, recipe):
          self.active = False
          self.recipe = recipe
  
      def toggle(self):
          if not self.active:
              self.active = True
              self.run()
  
          else:
              self.active = False
              # How can this stop flag be passed into the running thread?
              cookingThread.stopThread = True
  
  
      def run(self):
          cookingThread = CookingThread(self.recipe)
          cookingThread.start()
  </code></pre>
  
  <p><strong>CookingThread</strong></p>
  
  <pre><code>class CookingThread(threading.Thread):
  
      def __init__(self, recipe):
          super(CookingThread, self).__init__()
          self.recipe = recipe
          self.stopThread = False
  
      def run(self):
          for i in range(self.recipe):
              # Check if we should stop the thread
              if self.stopThread:
                  return
              else:
                  print 'Cooking...'
                  time.sleep(1)
  </code></pre>
  
  <p><strong>Main</strong></p>
  
  <pre><code>cooker = Cooker(10)
  cooker.toggle()    # Starts the thread
  
  time.sleep(5)
  cooker.toggle()    # Stops the thread (does not work)
  </code></pre>