在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使用装饰器进行django开发实例代码

本文研究的主要是Python使用装饰器进行django开发的相关内容,具体如下。 装饰器可以给一个函数,方法或类进行加工,添加额外的功能。 在这篇中使用装饰器给页面添加session而不...

python实现文件的备份流程详解

python实现文件的备份流程详解

python实现输入要备份的文件名称:test.txt 12行代码实现文件备份功能 第一步:打开我们的pycharm软件,然后新建一个Python文件 第二步:新建好我们的Python文...

python中partial()基础用法说明

前言 一个函数可以有多个参数,而在有的情况下有的参数先得到,有的参数需要在后面的情景中才能知道,python 给我们提供了partial函数用于携带部分参数生成一个新函数。 在funct...

python自动格式化json文件的方法

本文实例讲述了python自动格式化json文件的方法。分享给大家供大家参考。具体如下: 这里主要实现将代码混乱的json文件格式化。 还有一小堆python常用算法代码 完整实例代码点...

简介二分查找算法与相关的Python实现示例

二分查找Binary Search的思想: 以有序表表示静态查找表时,查找函数可以用二分查找来实现。 二分查找(Binary Search)的查找过程是:先确定待查记录所在的区间,然后逐...