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

 1 import time
 2 import threading
 3 
 4 
 5 def fun():
 6     print "start fun"
 7     time.sleep(2)
 8     print "end fun"
 9 
10 
11 print "main thread"
12 t1 = threading.Thread(target=fun,args=())
13 
14 t1.setDaemon(True)
15 
16 t1.start()
17 time.sleep(1)
18 print "main thread end"

 

結果:

main thread
start fun
main thread end

結論:程序在主線程結束后,直接退出了。 導致子線程沒有運行完。

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM