在python中实现强制关闭线程的示例

yipeiwu_com6年前Python基础

如下所示:

import threading
import time
import inspect
import ctypes


def _async_raise(tid, exctype):
  """raises the exception, performs cleanup if needed"""
  tid = ctypes.c_long(tid)
  if not inspect.isclass(exctype):
   exctype = type(exctype)
  res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
  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("PyThreadState_SetAsyncExc failed")


def stop_thread(thread):
  _async_raise(thread.ident, SystemExit)


class TestThread(threading.Thread):
  def run(self):
   print
   "begin"
   while True:
     time.sleep(0.1)
   print('end')


if __name__ == "__main__":
  t = TestThread()
  t.start()
  time.sleep(1)
  stop_thread(t)
  print('stoped') 

以上这篇在python中实现强制关闭线程的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

opencv实现图片模糊和锐化操作

opencv实现图片模糊和锐化操作

本文为大家分享了opencv图片模糊和锐化的具体实现代码,供大家参考,具体内容如下 一、模糊操作 #!/usr/bin/env python # _*_ coding:utf-8...

python3+selenium自动化测试框架详解

python3+selenium自动化测试框架详解

背景 为了更好的发展自身的测试技能,应对测试行业以及互联网行业的迭代变化。自学python以及自动化测试。 虽然在2017年已经开始接触了selenium,期间是断断续续执行自动化测...

python删除指定类型(或非指定)的文件实例详解

本文实例分析了python删除指定类型(或非指定)的文件用法。分享给大家供大家参考。具体如下: 如下,删除目录下非源码文件 import os import string de...

pycharm的console输入实现换行的方法

pycharm的console输入实现换行的方法

有时输出内容很多,没有自动换行,如下图所示: 可以点击下图按钮,即可自动换行: 以上这篇pycharm的console输入实现换行的方法就是小编分享给大家的全部内容了,希望能给大家一...

详解python string类型 bytes类型 bytearray类型

 一、python3对文本和二进制数据做了区分。文本是Unicode编码,str类型,用于显示。二进制类型是bytes类型,用于存储和传输。bytes是byte的序列,而str...