在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调取任意数字资产钱包余额功能

当我们的资产放在交易所的时候,可以通过链接交易所的API使用Python来监控余额。 那资产放在钱包的时候,如何来监控余额呢? 任何数字资产都可以使用区块浏览器来查询余额,那我们只要从此...

python 控制Asterisk AMI接口外呼电话的例子

Asterisk 是一个开放源代码的软件VoIP PBX系统,我们用Asterisk 搭建企业内部电话系统。 Asterisk AMI的Asterisk管理接口。可以实现对Asteris...

Python基础知识_浅谈用户交互

Python基础知识_浅谈用户交互

1、raw_input(): raw_input()是python 的内建函数,通过读取控制台的输入与用户实现交互。 raw_input()可以让用户输入字符串(即等待用户输入内容),...

对Python定时任务的启动和停止方法详解

在python中我们可以使用APScheduler进行定时任务。 APScheduler的具体编码这里就不介绍了。主要说下在终端中启动和停止任务。 一、运行计划任务的python脚本...

Python实现密码薄文件读写操作

制作一个"密码薄",其可以存储一个网址,和一个密码(如 123456),请编写程序完成这个“密码薄”的增删改查功能,并且实现文件存储功能 D:\pytest_day\mimab...