在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实现的二叉树定义与遍历算法实例

python实现的二叉树定义与遍历算法实例

本文实例讲述了python实现的二叉树定义与遍历算法。分享给大家供大家参考,具体如下: 初学python,需要实现一个决策树,首先实践一下利用python实现一个二叉树数据结构。建树的时...

在Python中操作列表之list.extend()方法的使用

 extend()方法追加序列内容到列表。 语法 以下是extend()方法的语法: list.extend(seq) 参数    ...

Pycharm 设置自定义背景颜色的图文教程

Pycharm 设置自定义背景颜色的图文教程

Pycharm可以通过设置主题来设定背景颜色,但主题的背景颜色也仅仅局限特定的几种,通过如下的方式可以自定义背景颜色。 File——Settings——Editor——General——...

详解python中的time和datetime的常用方法

一、time的常用方法: import time,datetime # 时间有三种展现方式:时间戳,时间元组,格式化的时间 print(time.time())#当前时间戳 pri...

Python面向对象程序设计之类的定义与继承简单示例

本文实例讲述了Python面向对象程序设计之类的定义与继承。分享给大家供大家参考,具体如下: 定义类: class A: def __init__(self, name):...