在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实现使用request模块下载图片demo示例

Python实现使用request模块下载图片demo示例

本文实例讲述了Python实现使用request模块下载图片。分享给大家供大家参考,具体如下: 利用流传输下载图片 # -*- coding: utf-8 -*- import re...

Kali Linux安装ipython2 和 ipython3的方法

1、更新包管理 apt-get install update. 2、安装 pip3 :apt-get install python3-pip 3、安装ipython 2 : pip in...

在python中使用正则表达式查找可嵌套字符串组

在网上看到一个小需求,需要用正则表达式来处理。原需求如下: 找出文本中包含”因为……所以”的句子,并以两个词为中心对齐输出前后3个字,中间全输出,如果“因为”和“所以”中间还存在“因为”...

对python创建及引用动态变量名的示例讲解

实际上在python中用列表就可以实现动态变量名的管理,python中的列表中可以存储任何类型的元素: listA = [0,"str",B()] 上述列表分别存储了整数,字符串...

详解python中的json和字典dict

定义 python中,json和dict非常类似,都是key-value的形式,而且json、dict也可以非常方便的通过dumps、loads互转。既然都是key-value格式,为啥...