Python - 中斷執行緒



在多執行緒程式設計中,中斷執行緒是在特定條件下需要終止執行緒執行的常見需求。在多執行緒程式中,可能需要停止新執行緒中的任務。這可能是由於多種原因,例如:任務完成、應用程式關閉或其他外部條件。

在 Python 中,可以使用threading.Event 或線上程本身中設定終止標誌來中斷執行緒。這些方法允許您有效地中斷執行緒,確保資源得到正確釋放並且執行緒乾淨地退出。

使用事件物件中斷執行緒

中斷執行緒的一種直接方法是使用threading.Event 類。此類允許一個執行緒向另一個執行緒發出特定事件已發生的訊號。以下是如何使用 threading.Event 實現執行緒中斷:

示例

在這個例子中,我們有一個 MyThread 類。它的物件開始執行 run() 方法。主執行緒休眠一段時間,然後設定一個事件。在檢測到事件之前,run() 方法中的迴圈會繼續執行。一旦檢測到事件,迴圈就會終止。

from time import sleep
from threading import Thread
from threading import Event

class MyThread(Thread):
   def __init__(self, event):
      super(MyThread, self).__init__()
      self.event = event

   def run(self):
      i=0
      while True:
         i+=1
         print ('Child thread running...',i)
         sleep(0.5)
         if self.event.is_set():
            break
         print()
      print('Child Thread Interrupted')

event = Event()
thread1 = MyThread(event)
thread1.start()

sleep(3)
print('Main thread stopping child thread')
event.set()
thread1.join()

執行此程式碼時,將產生以下輸出

Child thread running... 1
Child thread running... 2
Child thread running... 3
Child thread running... 4
Child thread running... 5
Child thread running... 6
Main thread stopping child thread
Child Thread Interrupted

使用標誌中斷執行緒

中斷執行緒的另一種方法是使用執行緒定期檢查的標誌。此方法涉及線上程物件中設定標誌屬性,並在執行緒的執行迴圈中定期檢查其值。

示例

此示例演示瞭如何在 Python 多執行緒程式中使用標誌來控制和停止正在執行的執行緒。

import threading
import time

def foo():
    t = threading.current_thread()
    while getattr(t, "do_run", True):
        print("working on a task")
        time.sleep(1)
    print("Stopping the Thread after some time.")

# Create a thread
t = threading.Thread(target=foo)
t.start()

# Allow the thread to run for 5 seconds
time.sleep(5)

# Set the termination flag to stop the thread
t.do_run = False

執行此程式碼時,將產生以下輸出

working on a task
working on a task
working on a task
working on a task
working on a task
Stopping the Thread after some time.
廣告