Python-是否正确杀死/退出期货线程? [英] Python - Properly Kill/Exit Futures Thread?

查看:174
本文介绍了Python-是否正确杀死/退出期货线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was previously using the threading.Thread module. Now I'm using concurrent.futures -> ThreadPoolExecutor. Previously, I was using the following code to exit/kill/finish a thread:

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")

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

This doesn't appear to be working with futures interface. What's the best practice here? Just return? My threads are controlling Selenium instances. I need to make sure that when I kill a thread, the Selenium instance is torn down.

编辑:我已经看到过被引用为重复的帖子。这是不够的,因为当您冒险涉足诸如期货之类的行为时,行为可能会截然不同。对于以前的线程模块,我的 terminate_thread 函数是可以接受的,不适用于对其他问题的批评。它与杀人不同。请看一下我发布的代码。

I had already seen the post that is referenced as duplicate. It's insufficient because when you venture into something like futures, behaviors can be radically different. In the case of the previous threading module, my terminate_thread function is acceptable and not applicable to the criticism of the other q/a. It's not the same as "killing". Please take a look at the code I posted to see that.

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

I don't want to kill. I want to check if its still alive and gracefully exit the thread in the most proper way. How to do with futures?

推荐答案

如果要让线程完成其当前工作,请执行以下操作:

If you want to let the threads finish their current work use:

thread_executor.shutdown(wait=True)

如果您想对当前的期货进行猛烈打击并停止所有...期货...(嘿)期货使用:

If you want to bash the current futures being run on the head and stop all ...future...(heh) futures use:

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

这使用您的terminate_thread函数在线程池执行程序的线程中调用异常。那些被破坏的期货将以例外设置返回。

This uses your terminate_thread function to call an exception in the threads in the thread pool executor. Those futures that were disrupted will return with the exception set.

这篇关于Python-是否正确杀死/退出期货线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆