多執行緒執行任務時,某個執行緒拋異常,如何讓程式立即退出

eliwang發表於2024-11-24
可以使用os._exit(1)
import threading
import time
import os

def worker(name):
    try:
        while True:
            print(f"Thread {name} is working...")
            time.sleep(1)
            if name == "Thread-2":
                raise Exception("Error in Thread-2")
    except Exception as e:
        print(f"Error occurred in {name}: {str(e)}")
        os._exit(1)

# 建立多個執行緒
threads = []
for i in range(3):
    t = threading.Thread(target=worker, args=(f"Thread-{i+1}",))
    threads.append(t)
    t.start()

# 等待所有執行緒完成
for t in threads:
    t.join()

相關文章