Python 主要透過 thread 與 threading 兩個模組提供多執行緒支援。thread 較為底層,threading 則在其上做了一層封裝,使用起來更順手。不過 CPython 受 GIL 限制,threading 無法真正把多核 CPU 的算力吃滿;若目標是計算密集型任務,該考慮 multiprocessing(在 Windows 下會遇到不少問題)。
若對執行緒有更高要求,也可以關注 Stackless Python。它是 Python 的變體,對多執行緒支援更好,並提供微線程(microthread)——一種更輕量的執行緒,切換開銷與資源佔用都更低。
一是把可執行方法(或可呼叫物件)直接交給 Thread:threading.Thread(target=executable_method);二是繼承 threading.Thread 並重寫 run()。第二種寫法中唯一必須重寫的是 run(),__init__() 視需要決定;但一旦重寫 __init__(),父類的 __init__() 必須放在函式第一行呼叫,否則會拋出「AssertionError: Thread.__init__() not called」。
threading 模組並未提供終止線程的方法。由 Thread() 啟動的線程彼此獨立,A 中啟動 B,A、B 各自運行。若想讓 A 結束時順帶結束 B,最省事的寫法是 B.setDaemon(True),但代價是 B 打開的檔案、傳輸中的資料可能來不及正確釋放。因此更妥當的做法是用 Event 機制,讓子線程自己收尾。
下面這段程式對比了兩種終止方式的差別:
import threading
import time
class mythread(threading.Thread):
def __init__(self, stopevt=None, File=None, name='subthread', Type='event'):
threading.Thread.__init__(self)
self.stopevt = stopevt
self.name = name
self.File = File
self.Type = Type
def Eventrun(self):
while not self.stopevt.isSet():
print(self.name + ' alive')
time.sleep(2)
if self.File:
print('close opened file in ' + self.name)
self.File.close()
print(self.name + ' stoped')
def Daemonrun(self):
D = mythreadDaemon(self.File)
D.setDaemon(True)
while not self.stopevt.isSet():
print(self.name + ' alive')
time.sleep(2)
print(self.name + ' stoped')
def run(self):
if self.Type == 'event':
self.Eventrun()
else:
self.Daemonrun()
class mythreadDaemon(threading.Thread):
def __init__(self, File=None, name='Daemonthread'):
threading.Thread.__init__(self)
self.name = name
self.File = File
def run(self):
while True:
print(self.name + ' alive')
time.sleep(2)
if self.File:
print('close opened file in ' + self.name)
self.File.close()
print(self.name + ' stoped')
def evtstop():
stopevt = threading.Event()
FileA = open('testA.txt', 'w')
FileB = open('testB.txt', 'w')
A = mythread(stopevt, FileA, 'subthreadA')
B = mythread(stopevt, FileB, 'subthreadB')
A.start(); B.start()
time.sleep(1)
print('send stop signal')
stopevt.set()
A.join(); B.join()
print('after A stoped, testA.txt closed? ' + repr(FileA.closed))
print('after A stoped, testB.txt closed? ' + repr(FileB.closed))
def daemonstop():
stopevt = threading.Event()
FileA = open('testA.txt', 'r')
A = mythread(stopevt, FileA, 'subthreadA', Type='Daemon')
A.start()
time.sleep(1)
stopevt.set()
A.join()
print('after A stoped, testA.txt closed? ' + repr(FileA.closed))
if not FileA.closed:
print('差別就在這裡:setDaemon() 無法保證子線程資源被釋放')
FileA.close()
if __name__ == '__main__':
evtstop()
daemonstop()
運行結果重點對比:Event 方式下,主線程發出停止訊號後,兩個子線程都先關閉各自檔案再退出,testA.txt 與 testB.txt 的 closed 均為 True;而 Daemon 方式下子線程被直接丟棄,testA.txt 的 closed 仍是 False——資源並未被正確釋放。
結論很直接:需要優雅收尾時,用 Event(或類似的旗標)通知子線程自行結束,而不是依賴 setDaemon()。