我是一名自学编程的学生,所以我很抱歉可能存在一些业余的错误。我想学习一些更深入的主题,因此我正在尝试理解线程和异常处理。
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)
这个脚本只是在随机时间启动和停止线程,如果收到^C
,它将终止程序。我注意到当某些线程完成时,它不会打印输出:
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!
在此示例中,它从未说明退出线程5。我发现,如果我注释掉
t.daemon = True
语句,可以解决这个问题,但是异常处理将等待任何线程完成。Starting thread 1
Starting thread 2
^C
Exiting thread 1
Exiting thread 2
我可以理解在处理线程时,最好让它们完成正在处理的任务后再退出,但是我只是好奇为什么要这样做。我非常感谢有关线程和守护进程本质的任何答案,以指导我的理解。