1. 程式人生 > >python使用Thread的setDaemon啟動後臺執行緒

python使用Thread的setDaemon啟動後臺執行緒

多執行緒程式設計當中, 執行緒的存在形態比較抽象. 通過前臺執行緒\後臺執行緒, 可以有效理解執行緒執行順序.(複雜的多執行緒程式可以通過設定執行緒優先順序實現)
後臺執行緒與前臺執行緒的直接區別是,
1)setDaemon(True): 當主執行緒退出時,後臺執行緒隨機退出;
2)setDaemon(False)(預設情況): 當主執行緒退出時,若前臺執行緒還未結束,則等待所有執行緒結束,相當於在程式末尾加入join().

例項:
例子描述:主執行緒呼叫giveures給出字串s的md5摘要,同時在giveures當中啟動一個執行緒列印字串內容.

1.前臺執行緒

import
time from hashlib import md5 from threading import Thread def pmd(md): time.sleep(3) #使用sleep使得該執行緒比主執行緒晚結束 print("backend recording:",md) def giveures(s): md = md5(s.encode('utf-8')) res = md.digest() t = Thread(target=pmd,args=(s,)) #t.setDaemon(True) 預設情況:t.setDaemon(False)
t.start() return res s = 'chrisyang' res = giveures(s) print(res) exit()

執行結果:

b'h#\x86|\xa0\xeff\xc7u\xba\x18\xb2\xd2s\xf9\x9e'
backend recording: chrisyang

第一行打印出來之後,隔3s後打印出第二行,說明在等待pmd執行緒結束後進程才退出.

2.後臺執行緒

import time
from hashlib import md5
from threading import Thread

def pmd(md)
:
time.sleep(3) #使用sleep使得該執行緒比主執行緒晚結束 print("backend recording:",md) def giveures(s): md = md5(s.encode('utf-8')) res = md.digest() t = Thread(target=pmd,args=(s,)) t.setDaemon(True) t.start() return res s = 'chrisyang' res = giveures(s) print(res) exit()

執行結果:

b'h#\x86|\xa0\xeff\xc7u\xba\x18\xb2\xd2s\xf9\x9e'

pmd執行緒因為sleep掛起一段時間,因此在主執行緒完成時還未結束就被強制退出了.

知識歸納:

以上的是前後臺執行緒的外在區別,至於內在區別,轉自Stack Overflow的一個精煉回答:
後臺執行緒的責任是為整個主執行緒提供服務,如保持網路連線(傳送keep-alive心跳包),負責記憶體管理與垃圾回收(實際上JVM就是這樣做的). 因此這些執行緒與實際提供應用服務的執行緒有了邏輯上的”前/後”的概念,而如果主執行緒已經退出,那麼後臺執行緒也沒有存在的必要.
如果沒有這一機制,那麼我們在主執行緒完成之後,還必須逐個地檢查後臺執行緒,然後在主執行緒退出之前,逐個地關閉它們. 有了前後執行緒的區分, 我們只需要負責管理前臺執行緒, 完成主要的邏輯處理之後退出即可.

原文:

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it’s okay to kill them off once the other, non-daemon, threads have exited.

Without daemon threads, you’d have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.