一、為什麼需要終止線程
在線程編程中,有時候需要終止線程的執行。這可能是由於程序需要在某個時間點停止某個線程的執行,或者線程執行遇到錯誤需要被終止,或者在用戶請求終止線程時需要將線程停止。無論是哪種情況,這都需要我們知道如何正確地終止線程。
二、使用stop()方式終止線程
在Python中,可以通過stop()方法來終止線程的執行,但是這種方式並不安全,因為stop()方法只是簡單地終止線程的執行,會導致線程所持有的鎖無法被釋放,從而導致程序發生死鎖。因此,我們通常不建議使用stop()方法來終止線程。
三、使用標誌位終止線程
使用標誌位來終止線程是一種更安全更有效的終止線程方式。一般情況下,我們為線程添加一個布爾型的標誌位,判斷標誌位是否為真,來控制線程的執行。當標誌位為假時,線程會停止執行。
import threading import time class myThread(threading.Thread): def __init__(self, threadID, name, flag): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.flag = flag def run(self): while self.flag: print("Thread " + self.name + " is running...") time.sleep(1) print("Thread " + self.name + " stopped.") def stop(self): self.flag = False t1 = myThread(1, "Thread 1", True) t2 = myThread(2, "Thread 2", True) t1.start() t2.start() time.sleep(5) t1.stop() t2.stop() t1.join() t2.join()
四、使用Thread類的事件對象終止線程
在Python的Thread類中,有一個事件對象,使用該事件對象可以控制線程的執行。當事件對象被設置為True時,線程會繼續執行,當事件對象被設置為False時,線程會停止執行。
import threading import time class myThread(threading.Thread): def __init__(self, threadID, name, event): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.event = event def run(self): while self.event.is_set(): print("Thread " + self.name + " is running...") time.sleep(1) print("Thread " + self.name + " stopped.") def stop(self): self.event.clear() t1_event = threading.Event() t1 = myThread(1, "Thread 1", t1_event) t2_event = threading.Event() t2 = myThread(2, "Thread 2", t2_event) t1_event.set() t2_event.set() t1.start() t2.start() time.sleep(5) t1.stop() t2.stop() t1.join() t2.join()
五、使用Thread類的terminate()方法終止線程
在Python3的Thread類中,有一個terminate()方法可以用來終止線程的執行。該方法會引發一個SystemExit異常,從而安全地退出線程。
import threading import time class myThread(threading.Thread): def __init__(self, threadID, name): threading.Thread.__init__(self) self.threadID = threadID self.name = name def run(self): while True: print("Thread " + self.name + " is running...") time.sleep(1) def stop(self): pass t1 = myThread(1, "Thread 1") t2 = myThread(2, "Thread 2") t1.start() t2.start() time.sleep(5) t1.terminate() t2.terminate() t1.join() t2.join()
原創文章,作者:QMSV,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/133559.html