多线程执行任务时,某个线程抛异常,如何让程序立即退出
可以使用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()