在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设计】。

相关文章

pandas.DataFrame删除/选取含有特定数值的行或列实例

pandas.DataFrame删除/选取含有特定数值的行或列实例

1.删除/选取某列含有特殊数值的行 import pandas as pd import numpy as np a=np.array([[1,2,3],[4,5,6],[7,8...

对Django 转发和重定向的实例详解

对Django 转发和重定向的实例详解

转发和重定向: 转发:一次请求和响应,请求的地址没有发生变化,如果此时刷新页面,就会出现重做现象。 重定向:一次以上的请求和响应,请求地址发生一次以上的变化,如果此时刷新页面,就不会发生...

Python标准模块--ContextManager上下文管理器的具体用法

写代码时,我们希望把一些操作放到一个代码块中,这样在代码块中执行时就可以保持在某种运行状态,而当离开该代码块时就执行另一个操作,结束当前状态;所以,简单来说,上下文管理器的目的就是规定对...

python for循环输入一个矩阵的实例

代码如下: a=[] for i in range(3): a.append([]) for j in range(3): a[i].append(int(input(...

在Python中处理时间之clock()方法的使用

 clock()方法返回当前的处理器时间,以秒表示Unix上一个浮点数。精度取决于具有相同名称的C函数,但在任何情况下,这是使用于基准Python或定时的算法函数。 在Wind...