子執行緒的強制性終止是我們實際應用時經常需要用到的,然而python官方並沒有給出相關的函式來處理這種情況。網上找到乙個挺合理的解決方案,這裡分享給大家。
import threading
import time
import inspect
import ctypes
def _async_raise(tid, exctype):
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.pythreadstate_setasyncexc(tid, ctypes.py_object(exctype))
if res == 0:
raise valueerror("invalid 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(tid, none)
raise systemerror("pythreadstate_setasyncexc failed")
def stop_thread(thread):
_async_raise(thread.ident, systemexit)
def test():
while true:
print('-------')
time.sleep(0.5)
if __name__ == "__main__":
t = threading.thread(target=test)
t.start()
time.sleep(5.2)
print("main thread sleep finish")
stop_thread(t)
Python 強制停止子執行緒
timer 一般會設定乙個間隔時間,然後才開乙個子執行緒執行需要執行的函式。cancel 函式只能取消還未開始執行的 timer,也就是取消該 timer。如果 timer 已經開啟子執行緒執行函式了,用 cancel 函式 是不能停止子執行緒執行的,子執行緒會一直執行,直到結束。cancel st...
python 強制停止執行緒
2020 12 13更新 ctypes終止執行緒 coding utf 8 import threading import time import ctypes import inspect import asyncio def async raise tid,exctype raises the ...
外部執行緒停止Java子執行緒的方法
一 thread.stop 官方不推薦,because it is inherently unsafe.二 方式一 1.執行緒類示例 public class threadt1 implements runnable public void stop public void run system.o...