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

yipeiwu_com5年前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设计】。

相关文章

利用django-suit模板添加自定义的菜单、页面及设置访问权限

前言 本文主要给大家介绍了利用django-suit模板在管理后台添加自定义的菜单和自定义的页面、设置访问权限的相关内容,分享出来供大家参考学习,下面话不多说了,来随着小编一起看看详细的...

详解Python中time()方法的使用的教程

 time()方法返回时间,在UTC时代以秒表示浮点数。 注意:尽管在时间总是返回作为一个浮点数,并不是所有的系统提供时间超过1秒精度。虽然这个函数正常返回非递减的值,就可以在...

78行Python代码实现现微信撤回消息功能

78行Python代码实现现微信撤回消息功能

Python曾经对我说:"时日不多,赶紧用Python"。于是看到了一个基于python的微信开源库:itchat,玩了一天,做了一个程序,把私聊撤回的信息可以收集起来并发送到个人微信的...

详解python实现识别手写MNIST数字集的程序

我们需要做的第⼀件事情是获取 MNIST 数据。如果你是⼀个 git ⽤⼾,那么你能够通过克隆这本书的代码仓库获得数据,实现我们的...

Python 转换RGB颜色值的示例代码

题目:转换RBG颜色值 我们知道在网页中的颜色值设置都是用16进制的RGB来表示的,比如#FFFFFF,表示R:255,G:255,B:255的白色。 现在请设计一个函数可以转换RGB...