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

#测试例子
threads = threading.Thread(target=doing)
threads.setDaemon(True) #设置守护线程目的尽量防止意外中断掉主线程程序,
threads.start()
time.sleep(5)

ret = kill_thread(threads, doing)
print(ret)
posted @ 2022-01-18 11:50  默*为  阅读(647)  评论(0编辑  收藏  举报