我以前使用過該threading.Thread模塊?,F(xiàn)在我正在使用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 實例被拆除。編輯:我已經(jīng)看到被引用為重復的帖子。這是不夠的,因為當你冒險進入像期貨這樣的東西時,行為可能會完全不同。在之前的線程模塊的情況下,我的terminate_thread功能是可以接受的,不適用于其他q/a的批評。這與“殺戮”不同。請查看我發(fā)布的代碼以了解這一點。我不想殺人。我想檢查它是否還活著并以最正確的方式優(yōu)雅地退出線程。期貨怎么做?
2 回答

慕桂英4014372
TA貢獻1871條經(jīng)驗 獲得超13個贊
如果您想讓線程完成當前的工作,請使用:
thread_executor.shutdown(wait=True)
如果您想打擊當前正在運行的期貨并停止所有...future...(heh) 期貨,請使用:
thread_executor.shutdown(wait=False)
for t in thread_executor._threads:
terminate_thread(t)
這使用您的 terminate_thread 函數(shù)在線程池執(zhí)行程序中的線程中調(diào)用異常。那些被打亂的期貨將返回并設(shè)置異常。
添加回答
舉報
0/150
提交
取消