Python Threading / Daemon

Self-taught student, so I apologize for all amateur errors. I want to learn some deeper topics, so I'm trying to understand threading and exception handling.

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)

This script simply starts and stops threads after a random time and will kill the program if it receives ^C. I noticed that it does not print when some threads end:

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!

In this example, it never states that it exits thread 5. I find that I can fix this if I comment on the instruction t.daemon = True, but then the exception handling waits for any threads to complete.

Starting thread 1
Starting thread 2
^C
Exiting thread 1
Exiting thread 2

, , , , . , , .

+4
1

, , . :

" ". , Python , . . daemon .

. Daemon . ( , ..) . , , - , .

. 3 5. 5 1 10 . , 70% , , " !" . 5 5 . 5 , " 5".

, - , , .

+4

All Articles