在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实现的朴素贝叶斯算法经典示例【测试可用】

本文实例讲述了Python实现的朴素贝叶斯算法。分享给大家供大家参考,具体如下: 代码主要参考机器学习实战那本书,发现最近老外的书确实比中国人写的好,由浅入深,代码通俗易懂,不多说上代码...

python opencv 直方图反向投影的方法

python opencv 直方图反向投影的方法

本文介绍了python opencv 直方图反向投影的方法,分享给大家,具体如下: 目标: 直方图反向投影 原理: 反向投影可以用来做图像分割,寻找感兴趣区间。它会输出与输入图像...

Python文件读写常见用法总结

1. 读取文件 # !/usr/bin/env python # -*- coding:utf-8 -*- """ 文件读取三步骤: 1.打开文件 f=open(file...

Python 正则表达式入门(初级篇)

引子 首先说 正则表达式是什么? 正则表达式,又称正规表示式、正规表示法、正规表达式、规则表达式、常规表示法(英语:Regular Expression,在代码中常简写为regex、re...

Python的Django框架可适配的各种数据库介绍

在 Django 中使用 PostgreSQL 使用 PostgreSQL 的话,你需要从 http://www.djangoproject.com/r/python-pgsql/ 下载...