python开两个守护线程_python 守护线程
生活随笔
收集整理的這篇文章主要介紹了
python开两个守护线程_python 守护线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
守護線程
如果python線程是守護線程,那么以為著這個線程是“不重要”的,“不重要”意味著如果他的父進程結束了但該守護線程沒有運行完,守護進程就會被強制結束。如果線程是非守護線程,那么父進程只有等到守護線程運行完畢后才能結束。
在python中,線程通過threadName.setDaemon(True|False)來設置是否為守護線程
代碼實例
父進程中調用兩個線程,但父進程會瞬間運行完,觀察兩個線程的運行情況。
import time import threadingdef write(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, end_time)print(string)def watch(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, end_time)print(string)threads = [] t1 = threading.Thread(target=write, args=("poem",)) t2 = threading.Thread(target=watch, args=("video",)) threads.append(t1) threads.append(t2)def for_test():for thread in threads:thread.setDaemon(False)thread.start()print("main over")if __name__ == '__main__':for_test()運行結果:
可以看到主線程瞬間結束,但是等待到子線程均運行完畢之后程序才退出。
import time import threadingdef write(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start writting %s at %s" % (content, end_time)print(string)def watch(content):start_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, start_time)print(string)time.sleep(5)end_time = time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))string = "start watching %s at %s" % (content, end_time)print(string)threads = [] t1 = threading.Thread(target=write, args=("poem",)) t2 = threading.Thread(target=watch, args=("video",)) threads.append(t1) threads.append(t2)def for_test():for thread in threads:thread.setDaemon(True)thread.start()if __name__ == '__main__':print("main start a t %s" %(time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))))for_test()print("main end at %s" %(time.strftime("%Y/%m/%d-%H:%M:%S", time.localtime(time.time()))))運行結果:
我們可以看到主線程結束之后整個程序即退出了。
更新時間: 2019 11 12
總結
以上是生活随笔為你收集整理的python开两个守护线程_python 守护线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java List集合转换相关操作
- 下一篇: python编辑学生分数_python处