python 使用异常来中断/暂停线程
2022/1/18 12:34:26
本文主要是介绍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 使用异常来中断/暂停线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python