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

相关文章

用Python将动态GIF图片倒放播放的方法

用Python将动态GIF图片倒放播放的方法

这次让我们一个用 Python 做一个小工具:将动态 GIF 图片倒序播放! GIF(Graphics Interchange Format) 是一种可以用来呈现动画效果的图片格式,原...

Python list运算操作代码实例解析

这篇文章主要介绍了Python list运算操作代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下   在操作list的时候,...

调试Python程序代码的几种方法总结

程序能一次写完并正常运行的概率很小,基本不超过1%。总会有各种各样的bug需要修正。有的bug很简单,看看错误信息就知道,有的bug很复杂,我们需要知道出错时,哪些变量的值是正确的,哪些...

Python2.7.10以上pip更新及其他包的安装教程

Python2.7.10以上pip更新及其他包的安装教程

Python2.7还是一个比较稳定的版本,目前80%以上的公司都在使用python2.7的版本。他不会在安装的时候报编码错误之类的问题。 但是从官网下载的Python上面自带的pip都是...

python实现桌面壁纸切换功能

本文实例为大家分享了python实现桌面壁纸切换功能的具体实现方法,供大家参考,具体内容如下 大体分为两个部分 一、利用爬虫爬取壁纸 第一部分爬取图片url地址并且下载至本地 爬虫针对...