在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的turtle模块实现给女票画个小心心

用python的turtle模块实现给女票画个小心心

晚上自习无聊 正好拿自己的平板电脑用python写了个小程序,运用turtle模块画一个小心心,并在心上画女票名字的首字母缩写,单纯只为红颜一笑。 代码贴出来,很简单 import...

浅谈PyQt5中异步刷新UI和Python多线程总结

目前任务需要做一个界面程序,PyQt是非常方便的选择,QT丰富的控件以及python方便的编程。近期遇到界面中执行一些后台任务时界面卡死的情况,解决了在这里记录下。 PyQt PyQt简...

python实现socket客户端和服务端简单示例

复制代码 代码如下:import socket#socket通信客户端def client():    mysocket=socket.socket(soc...

python安装numpy&安装matplotlib& scipy的教程

python安装numpy&安装matplotlib& scipy的教程

numpy安装 下载地址:https://pypi.python.org/pypi/numpy(各取所需) copy安装目录。eg:鄙人的D:\python3.6.1\Scripts p...

Python编程实现删除VC临时文件及Debug目录的方法

本文实例讲述了Python编程实现删除VC临时文件及Debug目录的方法。分享给大家供大家参考,具体如下: # *_* coding=gb2312 *-* import os imp...