title: Python: Kill Thread
body: <p>I am launching a main <code>Thread</code> from my <code>Python 3.4</code> program that launches various subthreads (in this case <code>daemon</code> threads).</p>
  
  <p><strong>I would like to kill the main thread and start it back up again.</strong> </p>
  
  <p>For some reason this is an incredibly difficult task. Before someone suggests that I use a <code>multiprocessing.Process</code> and <code>Process.terminate()</code> instead of a <code>Thread</code>, I am unable to go this route because my real program has to share a common <code>sqlite3</code> connection with all the threads and subthreads, which I cannot do using processes.</p>
  
  <p><strong>Currently, I am using a <code>Queue</code> to signal to the main thread that it should exit using <code>sys.exit()</code>, but this does not work, as you can see below.</strong> I've tried <code>os._exit(0)</code> instead, but that kills the whole interpreter.</p>
  
  <pre><code>import sys
  import time
  from threading import Thread
  from queue import Queue
  
  t = None
  q = None
  
  
  def subthread1():
      while True:
          time.sleep(2)
          print(' 1...')
  
  
  def subthread2():
      while True:
          time.sleep(2)
          print(' 2...')
  
  
  def main_thread(q):
  
      t1 = Thread(target=subthread1)
      t1.daemon = True
      t1.start()
  
      t2 = Thread(target=subthread2)
      t2.daemon = True
      t2.start()
  
      while True:
          msg = q.get()
  
          if msg == 0:
              print("EXITING THREAD")
              sys.exit()
  
  
  def start():
      print("STARTING")
      global q, t
      q = Queue()
      t = Thread(target=main_thread, args=(q,))
      t.start()
  
  
  def kill():
      print("KILLING")
      global q, t
      q.put(0)
  
  
  def main():
      start()
      time.sleep(10)
      kill()
      time.sleep(10)
      start()
  
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <p><strong>This produces output:</strong></p>
  
  <pre><code>STARTING      
   1...         
   2...         
   1...         
   2...         
   2...         
   1...         
   1...         
   2...         
   2...         
   1...         
  KILLING       
  EXITING THREAD
   2...         
   1...         
   1...         
   2...         
   2...         
   1...         
   2...         
   1...         
  STARTING      
   2...         
   1...         
   2...         
   1...         
   2...         
   1...         
   2...         
   1...         
   2...         
   1...         
   1...         
   2...         
   1...         
   2...         
   1...         
  </code></pre>
  
  <p><strong>I want the main thread, including all subthreads, to exit, and then start up again. How can I achieve this? In my real program my subthreads have subthreads (all daemon). Any help greatly appreciated!</strong></p>