在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 pandas实现excel工作表合并功能详解

Python pandas实现excel工作表合并功能详解

import os,pandas as pd,re #1.获取文件夹下要合并的文件名 dirpath = '文件夹地址' #工作表3特殊处理 需要开始下标和结束下标 begin =...

python模块restful使用方法实例

python模块restful使用方法实例

RESTful架构,目前是比较流行的一种互联网软件架构。REST,即Representational State Transfer的缩写。 说白点就是网站即软件,再白点就是一个服务软件支...

python模拟登录百度贴吧(百度贴吧登录)实例

python模拟登录百度贴吧(百度贴吧登录)实例

 复制代码 代码如下:# -*- coding:utf-8 -*-# python3.3.3 import sys,time,re,urllib.parse,u...

给我一面国旗 python帮你实现

给我一面国旗 python帮你实现

本文实例为大家分享了Python之给我一面国旗的具体代码,供大家参考,具体内容如下 1、“给我一面国旗@微信官方” 今天“给我一面国旗@微信官方”刷爆了朋友圈,我也蹭波热度,出个Pyth...

基于树莓派的语音对话机器人

本文实例为大家分享了基于树莓派的语音对话机器人,供大家参考,具体内容如下 第一部分代码 arecord -D "plughw:1" -f S16_LE -r 16000 -d 3 /...