python 使用異常來中斷/暫停線程
""""
python 使用異常來中斷/暫停線程
h_thread 線程句柄
stoptype 線程停止類型,返回1則正常中斷了線程
"""
def doing():
ncout = 0
while 1:
ncout += 1
print(ncout)
time.sleep(0.1)
def kill_thread(h_thread, stoptype): #= SystemExit
import inspect
import ctypes
try:
"""raises the exception, performs cleanup if needed"""
tid = ctypes.c_long(h_thread.ident)
if not inspect.isclass(stoptype):
stoptype = type(stoptype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(stoptype))
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("kill_thread failed")
return res
except Exception as e:
print(e)
# return -1
#測(cè)試?yán)?br>threads = threading.Thread(target=doing)
threads.setDaemon(True) #設(shè)置守護(hù)線程目的盡量防止意外中斷掉主線程程序,
threads.start()
time.sleep(5)
ret = kill_thread(threads, doing)
print(ret)
本文來自博客園,作者:{archer},轉(zhuǎn)載請(qǐng)注明原文鏈接:http://www.rzrgm.cn/archer-mowei/p/15817182.html

浙公網(wǎng)安備 33010602011771號(hào)