Python教程

python 使用异常来中断/暂停线程

本文主要是介绍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)
这篇关于python 使用异常来中断/暂停线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!