我之前使用的是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")
这似乎无法与futures接口一起使用。这里有什么最佳实践?只需return
吗?我的线程正在控制Selenium实例。我需要确保在终止线程时,Selenium实例已被拆除。
编辑:我已经看到了被引用为重复的帖子。它不足以解决问题,因为当你涉足类似futures的东西时,行为可能会发生根本性的变化。在以前的线程模块中,我的terminate_thread
函数是可以接受的,并且不适用于其他q/a的批评。这不同于“杀死”。请查看我发布的代码。
我不想杀死线程。我想检查它是否仍然存活并以最合适的方式优雅地退出线程。如何在futures中进行操作?
StoppableThread
吗? - Athena