在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爱心表白的具体代码,供大家参考,具体内容如下 import turtle import time # 画爱心的顶部 def LittleHeart()...

举例讲解Python中的死锁、可重入锁和互斥锁

一、死锁 简单来说,死锁是一个资源被多次调用,而多次调用方都未能释放该资源就会造成死锁,这里结合例子说明下两种常见的死锁情况。 1、迭代死锁 该情况是一个线程“迭代”请求同一个资源,直接...

Python 音频生成器的实现示例

Python 音频生成器的实现示例

使用Python生成不同声音的音频 第一步先去百度AI中注册账号,在控制台中创建语音技术应用,获取AppID,API Key,Secret Key 第二步 引用 from tkin...

Python 除法小技巧

复制代码 代码如下:from __future__ import division print 7/3 输出结果: 2.3333333333...

在Django下创建项目以及设置settings.py教程

在Django下创建项目以及设置settings.py教程

进入虚拟环境创建目录(在虚拟环境下不要使用sudo命令) 1.在虚拟环境下安装需要的安装包(注意,不要用sudo命令,否则会安装到真实环境下) pip3 install Django==...