【问题标题】:Python - Properly Kill/Exit Futures Thread?Python - 正确杀死/退出期货线程?
【发布时间】:2019-03-08 22:28:34
【问题描述】:

我之前使用的是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")

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

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

我不想杀人。我想检查它是否还活着并以最合适的方式优雅地退出线程。期货怎么办?

【问题讨论】:

  • 请有人反对这样做的人。我四处搜索,找不到一个例子。想要杀死一个线程并不少见或不合理。
  • 好像是从stackoverflow.com/questions/323972/…复制过来的,你是不是也实现了StoppableThread
  • 问题已编辑
  • 我发现它有一个问题。在我将线程存储在列表中之前。现在我不是。也许我也可以存储期货并将它们传递进去。

标签: python python-3.x concurrency concurrent.futures


【解决方案1】:

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

thread_executor.shutdown(wait=True)

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

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

这使用您的 terminate_thread 函数在线程池执行程序的线程中调用异常。那些被打乱的 future 将返回异常集。

【讨论】:

【解决方案2】:

线程结果上的.cancel()怎么样?

cancel() 尝试取消呼叫。如果当前正在通话 已执行且无法取消,则该方法将返回 False, 否则调用将被取消,该方法将返回 True。

https://docs.python.org/3/library/concurrent.futures.html

【讨论】:

  • 您需要取消所有未来,并且不保证当前正在运行的任何未来都会被 .cancel() 停止
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 2018-11-26
  • 2018-08-06
  • 2017-08-05
相关资源
最近更新 更多