python 使用异常来中断/暂停线程
2024-09-08 19:18:02
""""
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)
最新文章
- Cenos7 编译安装 Mariadb Nginx PHP Memcache ZendOpcache (实测 笔记 Centos 7.0 + Mariadb 10.0.15 + Nginx 1.6.2 + PHP 5.5.19)
- Razor语法&;ActionResult&;MVC
- Selenium2+python自动化19-单选框和复选框(radiobox、checkbox)
- Javascript 严格模式
- hadoop 2.0 native
- TCP/IP协议原理与应用笔记21:路由选择的方法
- JavaScript高级---门面模式设计
- HighChart图片本地导出
- WEB黑客工具箱之LiveHttpHeaders介绍
- 四、MVC简介
- Treap(树堆)
- 《团队作业第三、第四周》五小福团队作业--Scrum 冲刺阶段--Day7
- [NOI2015]软件包管理器-树链剖分
- 隐藏非选中的checkBox
- [iOS]Xcode处理过时方法的警告
- nginx log 错误502 upstream sent too big header while reading response header from upstream
- java.lang.IndexOutOfBoundsException: setSpan (35 ... 35) ends beyond length 28
- 83.Linux之ubuntu-14.04.4-desktop-amd64安装
- java知识点总结
- 【JavaScript】实现复选框的全选、全部不选、反选