在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设计】。

相关文章

Python写的服务监控程序实例

前言: Redhat下安装Python2.7 rhel6.4自带的是2.6, 发现有的机器是python2.4。 到python网站下载源代码,解压到Redhat上,然后运行下面的命令:...

Django 用户认证组件使用详解

一、auth模块 # 创建超级用户 python manage.py createsuperuser from django.contrib import auth django...

分享一个简单的python读写文件脚本

先来看一段创建文件并写入文本的代码,然后作介绍。 #!/usr/bin/env python 'makeFile.py -- create a file'...

Python简单过滤字母和数字的方法小结

本文实例讲述了Python简单过滤字母和数字的方法。分享给大家供大家参考,具体如下: 实例1 crazystring = 'dade142.!0142f[., ]ad' # 只保留数...

python基础教程之元组操作使用详解

简介 tuple 1.元组是以圆括号“()”包围的数据集合,不同成员以“,”分隔。通过下标进行访问 2.不可变序列,可以看做不可变的列表,与列表不同:元组中数据一旦确立就不能改变(所以没...