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

相关文章

使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法

使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法

如下所示: # coding=utf-8 import pandas as pd # 读取csv文件 3列取名为 name,sex,births,后面参数格式为names= name...

Python列表list排列组合操作示例

本文实例讲述了Python列表list排列组合操作。分享给大家供大家参考,具体如下: 排列 例如: 输入为 ['1','2','3']和3 输出为 ['111','112','11...

深入探究Python中变量的拷贝和作用域问题

深入探究Python中变量的拷贝和作用域问题

在 python 中赋值语句总是建立对象的引用值,而不是复制对象。因此,python 变量更像是指针,而不是数据存储区域,  这点和大多数 OO 语言类似吧,比如 C++、...

Python3中条件控制、循环与函数的简易教程

Python3中条件控制、循环与函数的简易教程

一、条件控制 Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块,而计算机很多自动化任务,也是根据条件判断来实现的。 我们可以通过下图,来了解...

matplotlib作图添加表格实例代码

matplotlib作图添加表格实例代码

本文所示代码主要是通过Python+matplotlib实现作图,并且在图中添加表格的功能,具体如下。 代码 import matplotlib.pyplot as plt impo...