title: Python Threading/Daemon
body: <p>Self-taught programming student, so I apologize for all the amateur mistakes. I want to learn some deeper subjects, so I'm trying to understand threading, and exception handling. </p>
  
  <pre><code>import threading
  import sys
  from time import sleep
  from random import randint as r
  
  def waiter(n):
      print "Starting thread " + str(n)
      wait_time = r(1,10)
      sleep(wait_time)
      print "Exiting thread " + str(n)
  
  if __name__=='__main__':
      try:
          for i in range(5):
              t = threading.Thread(target=waiter, args=(i+1,))
              t.daemon = True
              t.start()
              sleep(3)
          print 'All threads complete!'
          sys.exit(1)
      except KeyboardInterrupt:
          print ''
          sys.exit(1)
  </code></pre>
  
  <p>This script just starts and stops threads after a random time and will kill the program if it receives a <code>^C</code>. I've noticed that it doesn't print when some threads finish:</p>
  
  <pre><code>Starting thread 1
  Starting thread 2
  Starting thread 3
  Exiting thread 3
  Exiting thread 2
  Starting thread 4
  Exiting thread 1
  Exiting thread 4
  Starting thread 5
  All threads complete!
  </code></pre>
  
  <p>In this example, it never states it exits thread 5. I find I can fix this if I comment out the <code>t.daemon = True</code> statement, but then exception handling waits for any threads to finish up.</p>
  
  <pre><code>Starting thread 1
  Starting thread 2
  ^C
  Exiting thread 1
  Exiting thread 2
  </code></pre>
  
  <p>I can understand that when dealing with threads, it's best that they complete what they're handling before exiting, but I'm just curious as to why this is. I'd really appreciate any answers regarding the nature of threading and daemons to guide my understanding.</p>