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

相关文章

Python random模块(获取随机数)常用方法和使用例子

random.randomrandom.random()用于生成一个0到1的随机符点数: 0 <= n < 1.0 random.uniformrandom.uniform(...

【Python】Python的urllib模块、urllib2模块批量进行网页下载文件

【Python】Python的urllib模块、urllib2模块批量进行网页下载文件

由于需要从某个网页上下载一些PDF文件,但是需要下载的PDF文件有几百个,所以不可能用人工点击来下载。正好Python有相关的模块,所以写了个程序来进行PDF文件的下载,顺便熟悉了Pyt...

pd.DataFrame统计各列数值多少的实例

如下所示: .count() #非空元素计算 .min() a #最小值 .max() #最大值 .idxmin() #最小值的位置,类似于R中的which.min函...

在Python中使用poplib模块收取邮件的教程

在Python中使用poplib模块收取邮件的教程

SMTP用于发送邮件,如果要收取邮件呢? 收取邮件就是编写一个MUA作为客户端,从MDA把邮件获取到用户的电脑或者手机上。收取邮件最常用的协议是POP协议,目前版本号是3,俗称POP3。...

Python实现字符串与数组相互转换功能示例

Python实现字符串与数组相互转换功能示例

本文实例讲述了Python实现字符串与数组相互转换功能。分享给大家供大家参考,具体如下: 字符串转数组 str = '1,2,3' arr = str.split(',') prin...