可以使用 threading.Event 来实现这个功能。

  1. 在程序运行前,初始化一个 Event 对象:
import threading

stop_event = threading.Event()
  1. 在每个等待的线程中,使用 wait 方法等待 Event 对象被设置:
stop_event.wait()
  1. 如果某个线程出错,可以通过调用 set 方法来设置 Event 对象,使其他等待的线程直接停止程序:
stop_event.set()

完整代码示例:

import threading
import time
import random

# 初始化 Event 对象
stop_event = threading.Event()

# 定义线程函数
def worker():
    try:
        print(f"Thread {threading.current_thread().name} is started.")
        # 模拟线程工作时间
        time.sleep(random.random() * 10)
        print(f"Thread {threading.current_thread().name} is finished.")
    except Exception as e:
        print(f"Thread {threading.current_thread().name} is stopped because of {e}.")
        # 设置 Event 对象,通知其他等待的线程直接停止程序
        stop_event.set()

# 创建多个线程
threads = []
for i in range(5):
    t = threading.Thread(target=worker, name=f"Thread-{i}")
    threads.append(t)

# 启动线程
for t in threads:
    t.start()

# 等待所有线程结束
for t in threads:
    t.join()

# 如果 Event 对象被设置,直接停止程序
if stop_event.is_set():
    print("Program is stopped because of error in some threads.")
else:
    print("Program is finished.")
Python 一个线程出错怎么让其他等待的线程不在等待直接停止程序

原文地址: https://www.cveoy.top/t/topic/wNH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录