在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生成MD5值的两种方法实例分析

本文实例讲述了Python生成MD5值的两种方法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- import datetime # NO.1 使用M...

PyCharm+PySpark远程调试的环境配置的方法

PyCharm+PySpark远程调试的环境配置的方法

前言:前两天准备用 Python 在 Spark 上处理量几十G的数据,熟料在利用PyCharm进行PySpark远程调试时掉入深坑,特写此博文以帮助同样深处坑中的bigdata&mac...

python tkinter库实现气泡屏保和锁屏

python tkinter库实现气泡屏保和锁屏

本文实例为大家分享了python tkinter库实现气泡屏保和锁屏的具体代码,供大家参考,具体内容如下 显示效果如下: 代码:  import random impor...

详谈Python高阶函数与函数装饰器(推荐)

详谈Python高阶函数与函数装饰器(推荐)

一、上节回顾 Python2与Python3字符编码问题,不管你是初学者还是已经对Python的项目了如指掌了,都会犯一些编码上面的错误。我在这里简单归纳Python3和Python2各...

在VS Code上搭建Python开发环境的方法

在VS Code上搭建Python开发环境的方法

1、下载安装 python https://www.python.org/downloads/windows/ web-based installer 在线安装 executable...