xen*_*ndi 10 python concurrency python-3.x concurrent.futures
我以前使用过该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")
Run Code Online (Sandbox Code Playgroud)
这似乎不适用于期货界面。这里的最佳做法是什么?只是return
?我的线程正在控制 Selenium 实例。我需要确保当我杀死一个线程时,Selenium 实例被拆除。
编辑:我已经看到被引用为重复的帖子。这是不够的,因为当你冒险进入像期货这样的东西时,行为可能会完全不同。在之前的线程模块的情况下,我的terminate_thread
功能是可以接受的,不适用于其他q/a的批评。这与“杀戮”不同。请查看我发布的代码以了解这一点。
我不想杀人。我想检查它是否还活着并以最正确的方式优雅地退出线程。期货怎么做?
Are*_*res -2
.cancel()
线程结果怎么样?
cancel() 尝试取消呼叫。如果调用当前正在执行且无法取消,则该方法将返回 False,否则调用将被取消,该方法将返回 True。
https://docs.python.org/3/library/concurrent.futures.html
归档时间: |
|
查看次数: |
8290 次 |
最近记录: |