守護執行緒會等待主線程執行完畢後被銷毀
需要強調的是:執行完畢並非終止執行
單執行緒:
import time
from threading import thread
def sayhi(name):
time.sleep(2)
print('%s say hello' % name)
if __name__ == '__main__':
t = thread(target=sayhi, args=('allen',))
# t.setdaemon(true) # 必須在t.start()之前設定
t.daemon = true
t.start()
print('主線程')
print(t.is_alive())
結果:主線程
true
多個執行緒:
import time
from threading import thread
def foo():
print(123)
time.sleep(5)
print('end123')
def bar():
print(456)
time.sleep(3)
print('end456')
if __name__ == '__main__':
t1 = thread(target=foo)
t2 = thread(target=bar)
t1.daemon = true
t1.start()
t2.start()
print('zhu...........')
結果:123
456zhu...........
end456
迷惑人的例子
import time
from threading import thread
def foo():
print(123)
time.sleep(1)
print('end123')
def bar():
print(456)
time.sleep(3)
print('end456')
if __name__ == '__main__':
t1 = thread(target=foo)
t2 = thread(target=bar)
t1.daemon = true
t1.start()
t2.start()
print('zhu...........')
結果:123
456zhu...........
end123
end456
Python 守護執行緒
python 守護執行緒 如果你想等待子執行緒完成再退出,那就什麼都不用做。或者顯示地呼叫thread.setdaemon false 設定daemon的值為false。新的子執行緒會繼承父執行緒的daemon標誌。整個python會在所有的非守護執行緒退出後才會結束,即程序中沒有非守護執行緒存在的...
python 守護執行緒
一 基礎概念 1 守護執行緒 在主線程 執行結束後,等待其它子執行緒執行結束,守護執行緒結束 2 守護程序 隨著主程序 執行結束,守護程序結束 3 主線程執行結束,它所在的程序執行結束 4 主程序 執行結束,主程序並沒結束,等待其它子程序執行結束並 資源 二 示例 守護執行緒 import time...
Python守護執行緒簡述
thread模組不支援守護執行緒的概念,當主線程退出時,所有的子執行緒都將終止,不管它們是否仍在工作,如果你不希望發生這種行為,就要引入守護執行緒的概念。threading模組支援守護執行緒,其工作方式是 守護執行緒一般是乙個等待客戶端請求服務的伺服器。如果沒有客戶端請求,守護執行緒就是空閒的,如果...