Python簡單實現多執行緒例子

只想安静的搬砖發表於2024-06-07

使用Python實現多執行緒的例子,演示如何在主執行緒內分別啟動ABC三個執行緒,並實現啟動和停止指定執行緒的功能

``
import threading
import time

  # 定義一個全域性標誌,用於控制執行緒的執行狀態
  stop_thread_A = False
  stop_thread_B = False
  stop_thread_C = False

  # 執行緒A的函式
  def thread_A():
      while not stop_thread_A:
          print("Thread A is running")
          time.sleep(1)
      print("Thread A is stopped")

  # 執行緒B的函式
  def thread_B():
      while not stop_thread_B:
          print("Thread B is running")
          time.sleep(1)
      print("Thread B is stopped")

  # 執行緒C的函式
  def thread_C():
      while not stop_thread_C:
          print("Thread C is running")
          time.sleep(1)
      print("Thread C is stopped")

  # 啟動執行緒的函式
  def start_threads():
      global thread_a, thread_b, thread_c

      # 建立執行緒
      thread_a = threading.Thread(target=thread_A)
      thread_b = threading.Thread(target=thread_B)
      thread_c = threading.Thread(target=thread_C)

      # 啟動執行緒
      thread_a.start()
      thread_b.start()
      thread_c.start()

  # 停止指定執行緒的函式
  def stop_thread(thread_name):
      global stop_thread_A, stop_thread_B, stop_thread_C

      if thread_name == 'A':
          stop_thread_A = True
      elif thread_name == 'B':
          stop_thread_B = True
      elif thread_name == 'C':
          stop_thread_C = True

  if __name__ == "__main__":
      # 啟動ABC三個執行緒
      start_threads()

      # 主執行緒等待5秒
      time.sleep(5)

      # 停止執行緒A
      stop_thread('A')

      # 主執行緒等待5秒
      time.sleep(5)

      # 停止執行緒B和C
      stop_thread('B')
      stop_thread('C')

      # 確保所有執行緒已經停止
      thread_a.join()
      thread_b.join()
      thread_c.join()

      print("All threads have been stopped")

``
注意事項
執行緒安全:在多執行緒程式設計中,訪問和修改共享資源時要小心,以避免競態條件和資料不一致問題。使用鎖(Lock)可以確保執行緒安全。
停止執行緒的方式:使用標誌變數來控制執行緒的停止是一個常見的方法,避免使用強制終止執行緒的方法(如threading.Thread的terminate()),因為這可能會導致資源未正確釋放等問題。
執行緒的生命週期:確保主執行緒在退出前等待所有子執行緒結束,使用join()方法可以確保這一點。
這個示例展示瞭如何使用Python的threading模組來啟動和停止執行緒,並解釋了相關的注意事項和程式碼細節。

相關文章