在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操作MySQL数据库实例详解【安装、连接、增删改查等】

本文实例讲述了Python操作MySQL数据库。分享给大家供大家参考,具体如下: 1、安装 通过Python连接MySQL数据库有很多库,这里使用官方推荐的MySQL Connector...

python调用cmd命令行制作刷博器

复制代码 代码如下:import webbrowser as webimport timeimport os count=0while count<10:  &...

Python语言实现将图片转化为html页面

Python语言实现将图片转化为html页面

PIL 图像处理库 PIL(Python Imaging Library) 是 Python 平台的图像处理标准库。不过 PIL 暂不支持 Python3,可以用 Pillow 代替,...

pip和pygal的安装实例教程 原创

pip和pygal的安装实例教程 原创

本文分为两个部分,第一部分是关于pip,第二部分关于pygal,主要关于二者的简介以及安装过程的分享,希望对大家有所帮助。 一、pip 1.简介 pip 是一个安装和管理 Python...

python pandas库中DataFrame对行和列的操作实例讲解

用pandas中的DataFrame时选取行或列: import numpy as np import pandas as pd from pandas import Sereis,...