Python守護線程用法實例
本文實例講述了Python守護線程用法。分享給大家供大家參考,具體如下:
如果你設置一個線程為守護線程,就表示你在說這個線程是不重要的,在進程退出的時候,不用等待這個線程退出。如果你的主線程在退出的時候,不用等待那些子線程完成,那就設置這些線程的daemon屬性。即在線程開始(thread.start())之前,調用setDeamon()函數,設定線程的daemon標志。(thread.setDaemon(True))就表示這個線程“不重要”。
如果你想等待子線程完成再退出,那就什么都不用做,或者顯示地調用thread.setDaemon(False),設置daemon的值為false。新的子線程會繼承父線程的daemon標志。整個Python會在所有的非守護線程退出后才會結束,即進程中沒有非守護線程存在的時候才結束。
看下面的例子:
import time import threading def fun(): print "start fun" time.sleep(2) print "end fun" print "main thread" t1 = threading.Thread(target=fun,args=()) #t1.setDaemon(True) t1.start() time.sleep(1) print "main thread end"
結果:
main thread start fun main thread end end fun
結論:程序在等待子線程結束,才退出了。
設置:setDaemon 為True
import time import threading def fun(): print "start fun" time.sleep(2) print "end fun" print "main thread" t1 = threading.Thread(target=fun,args=()) t1.setDaemon(True) t1.start() time.sleep(1) print "main thread end"
結果:
main thread start fun main thread end
結論:程序在主線程結束后,直接退出了。 導致子線程沒有運行完。
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python進程與線程操作技巧總結》、《Python Socket編程技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
Python實現搜索Google Scholar論文信息的示例代碼
這篇文章主要為大家詳細介紹了如何利用Python實現搜索Google Scholar論文信息的功能,文中的示例代碼講解詳細,需要的可以參考一下2023-03-03

