""""
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)

最新文章

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

热门文章

  1. Fast RCNN论文阅读笔记
  2. SQL29 计算用户的平均次日留存率
  3. windows11预览版装WSA心得
  4. css之transform属性的使用
  5. java 入门与进阶P-6.3+P-6.4
  6. springboot跨域解决
  7. Vue3 企业级优雅实战 - 组件库框架 - 11 组件库的打包构建和发布
  8. wsl ubuntu vscode 安装 Fira Code
  9. 汉诺塔 Java && Cpp 实现
  10. P7_小程序的宿主环境