在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中操作mysql的pymysql模块详解

前言 pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。但目前pymysql支持python3.x而后者不支持3.x版本。 本文测试python版本:...

使用TensorFlow实现简单线性回归模型

使用TensorFlow实现简单线性回归模型

本文使用TensorFlow实现最简单的线性回归模型,供大家参考,具体内容如下 线性拟合y=2.7x+0.6,代码如下: import tensorflow as tf import...

Python 窗体(tkinter)按钮 位置实例

如下所示: import tkinter def go(): #函数 print("go函数") win=tkinter.Tk() #构造窗体 win.title("he...

Python字典遍历操作实例小结

本文实例讲述了Python字典遍历操作。分享给大家供大家参考,具体如下: 1 遍历键值对 可以使用一个 for 循环以及方法 items() 来遍历这个字典的键值对。 dict =...