title: Causing a thread to stop while stuck within a while loop?
body: <p>Is is possible to stop a thread prematurely when it is stuck inside a while loop? Below is my sample code, which runs correctly, since each time it calls <code>loop_thread</code> it will check to see if the <code>threading.Event()</code> flag is set. When attempting to run the code for a file that processes information much longer than each second, there is no way to stop the entire function from continuing its execution until the next iteration. For example, if I run <code>dld_img_thread</code>, it takes about 5 minutes to complete its execution and recheck the while loop to see if should proceed. What I want to have happen is kill the <code>dld_img_thread</code> at a time shorter than 5 minutes (e.g. 1 minute). I don't care if the data is lost, just that the thread stops before the function finishes execution. Thank you</p>
  
  <pre><code>import threading, time, pythoncom, read_mt0
  import powerfail_debugport_reader as pf_dbg_rdr
  import powerfail_firmware_downloader as pf_fwdld
  
  
  def loop_thread(thread_name, thread_event):
      loopCnt = 0
      print "\nstarting {}".format(thread_name)
      print "is {0} alive? {1}\n".format(thread_name, L00P_thread.is_alive())
      while not thread_event.is_set():
          print("value of loopCnt = {}".format(loopCnt))
          loopCnt += 1
          time.sleep(1)
      print('stopping {}\n'.format(thread_name))
  
  def image_dld(thread_name, thread_event):
      pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
      print "\nstarting {}".format(thread_name)
      print "is {0} alive? {1}\n".format(thread_name, dld_img_thread.is_alive())
      while not thread_event.is_set():
          pf_fwdld.power_fail_test()
      print('stopping {}'.format(thread_name))
  
  def debug_port_thread(thread_name, thread_event):
      pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
      print "\nstarting {}".format(thread_name)
      print "is {0} alive? {1}\n".format(thread_name, debug_thread.is_alive())
      pf_dbg_rdr.debug_port_reader()
      print('\nstopping {}'.format(thread_name))
  
  def main():
      global L00P_thread, debug_thread
      pf_dbg_rdr.samurai_event = threading.Event()
  
      L00P_thread = threading.Thread(target=loop_thread, \
          args=('L00P_thread', pf_dbg_rdr.samurai_event))
  
      dld_img_thread = threading.Thread(target=image_dld, \
          args=('image_download', pf_dbg_rdr.samurai_event))
  
      debug_thread = threading.Thread(target=debug_port_thread, \
          args=('debug_port_reader', pf_dbg_rdr.samurai_event))
  
      L00P_thread.start()
      dld_img_thread.start()
      debug_thread.start()
      debug_thread.join()
  
  if __name__ == '__main__':
      main()
      print('processes stopped')
      print "Exiting Main Thread"
  </code></pre>