Skip to main content
 首页 » 编程设计

Python之正确杀死/退出 future 线程

2025年05月04日10tuyile006

我之前使用的是 threading.Thread 模块。现在我正在使用 concurrent.futures -> ThreadPoolExecutor。以前,我使用以下代码退出/终止/完成一个线程:

def terminate_thread(thread): 
    """Terminates a python thread from another thread. 
 
    :param thread: a threading.Thread instance 
    """ 
    if not thread.isAlive(): 
        return 
 
    exc = ctypes.py_object(SystemExit) 
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc( 
        ctypes.c_long(thread.ident), exc) 
    if res == 0: 
        raise ValueError("nonexistent thread id") 
    elif res > 1: 
        # """if it returns a number greater than one, you're in trouble, 
        # and you should call it again with exc=NULL to revert the effect""" 
        ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) 
        raise SystemError("PyThreadState_SetAsyncExc failed") 

这似乎不适用于 future 界面。这里的最佳做法是什么?只是返回?我的线程正在控制 Selenium 实例。我需要确保当我终止一个线程时,Selenium 实例被拆除。

编辑:我已经看到被引用为重复的帖子。这是不够的,因为当你冒险进入 future 之类的领域时,行为可能会截然不同。之前threading模块的情况下,我的terminate_thread函数是可以接受的,不适用于其他q/a的批评。这与“杀戮”不同。请查看我发布的代码以了解这一点。

我不想杀人。我想检查它是否仍然存在并以最适当的方式优雅地退出线程。 future 怎么办?

请您参考如下方法:

如果你想让线程完成他们当前的工作使用:

thread_executor.shutdown(wait=True) 

如果你想打击当前正在运行的 future 并停止所有...... future ......(嘿) future 使用:

thread_executor.shutdown(wait=False) 
for t in thread_executor._threads: 
    terminate_thread(t) 

这使用您的 terminate_thread 函数在线程池执行器的线程中调用异常。那些被中断的 future 将返回并设置异常。