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

相关文章

Django objects的查询结果转化为json的三种方式的方法

Django objects的查询结果转化为json的三种方式的方法

第一种方式: 利用seriallizers 这个方法,官网的解释说:将复杂的数据结构变成json、xml或者其他的格式 import json from django.core...

使用python在校内发人人网状态(人人网看状态)

复制代码 代码如下:#_*_coding:utf_8_ from sgmllib import SGMLParserimport sys, urllib2, urllib, cookie...

Python Web框架Flask中使用新浪SAE云存储实例

对于部署在新浪应用引擎SAE上的项目,使用新浪SAE云存储是不错的存储方案。 新浪SAE云存储仅能在SAE环境中正常使用,对它进行简单封装后,可以直接在Flask中使用,项目代码见Git...

python内置函数:lambda、map、filter简单介绍

lambda lambda可以理解为一种小函数,但是它是一个表达式,而不是一个语句,所以在def不允许出现的地方仍然可以使用lambda函数,例如list里。但是lambda内只可以执行...

Python实现批量修改图片格式和大小的方法【opencv库与PIL库】

Python实现批量修改图片格式和大小的方法【opencv库与PIL库】

本文实例讲述了Python实现批量修改图片格式和大小的方法。分享给大家供大家参考,具体如下: 第一种方法用到opencv库 import os import time import...