萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 多線程錯誤修正:RuntimeError: thread.__init__() not called

錯誤原因

繼承 threading.Thread 時,子類 __init__ 必須顯式呼叫父類建構子,否則線程物件未正確初始化,啟動時拋出 RuntimeError: thread.__init__() not called。

錯誤代碼


import threading

class NotifyThread(threading.Thread):
    def __init__(self, params):
        # 缺少父類初始化!
        self.params = params
    
    def run(self):
        print("start notify...")
        # 處理邏輯
        print("end notify...")

t = NotifyThread({'key': 'value'})
t.start()  # 拋出 RuntimeError

正確寫法


class NotifyThread(threading.Thread):
    def __init__(self, params):
        # 必須先呼叫父類 __init__
        threading.Thread.__init__(self)
        # 或 Python 3: super().__init__()
        self.params = params
    
    def run(self):
        print("start notify...")
        # 處理邏輯
        print("end notify...")

完整範例:帶參數線程類


import threading
import time

class WorkerThread(threading.Thread):
    def __init__(self, task_id, data, callback=None):
        super().__init__(name=f"Worker-{task_id}")
        self.task_id = task_id
        self.data = data
        self.callback = callback
        self.result = None
        self.error = None
    
    def run(self):
        try:
            print(f"[{self.name}] 開始處理任務 {self.task_id}")
            # 模擬耗時操作
            time.sleep(2)
            self.result = f"任務 {self.task_id} 完成,輸入: {self.data}"
        except Exception as e:
            self.error = e
        finally:
            if self.callback:
                self.callback(self)

def on_complete(thread):
    if thread.error:
        print(f"[{thread.name}] 失敗: {thread.error}")
    else:
        print(f"[{thread.name}] 成功: {thread.result}")

# 使用
threads = []
for i in range(3):
    t = WorkerThread(i, f"data-{i}", callback=on_complete)
    threads.append(t)
    t.start()

for t in threads:
    t.join()

print("所有任務完成")

最佳實踐清單

  1. ✅ 子類 __init__ 首行呼叫 super().__init__() 或 threading.Thread.__init__(self)。
  2. ✅ 覆寫 run() 而非 start()。
  3. ✅ 使用 name 參數命名線程,利於除錯與日誌追蹤。
  4. ✅ 異常捕獲於 run() 內部,避免線程悄悄死亡。
  5. ✅ 共享資料使用 threading.Lock、Queue 或 ThreadLocal。

Python 2 與 3 差異

  • Python 2: threading.Thread.__init__(self) 或 super(NotifyThread, self).__init__()。
  • Python 3: 推薦 super().__init__(),更簡潔且支援協作繼承。
copyright © 萬盛學電腦網 all rights reserved