在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 循环终止语句的三种方法小结

在Python循环终止语句有三种: 1、break break用于退出本层循环 示例如下: while True: print "123" break print "45...

Python os模块中的isfile()和isdir()函数均返回false问题解决方法

今天在写一个linux下自动备份指定目录下的所有目录的脚本时,遇到了一个问题,由于我是需要备份目录,所以,需要判断扫描的文件是否为目录,当我用os.path.isdir()来判断的时候,...

python获取全国城市pm2.5、臭氧等空气质量过程解析

随着国家发展,中国很多城市的空气质量其实并不好,国家气象局会有实时统计,但是要去写爬虫爬取是十分麻烦的事情,并且官方网站也会做一些反爬虫措施,所以实现起来比较麻烦,最好的办法就是使用现成...

基于OpenCV python3实现证件照换背景的方法

基于OpenCV python3实现证件照换背景的方法

简述 生活中经常要用到各种要求的证件照电子版,红底,蓝底,白底等,大部分情况我们只有其中一种,所以通过技术手段进行合成,用ps处理证件照,由于技术不到位,有瑕疵,所以想用python&o...

Python3批量生成带logo的二维码方法

最近有个需求:批量生成带Logo的二维码 生成二维码比较简单,网上的资源也比较多,不赘述了。自己研究了一下加了logo并且美化了一下(网上的资源直接加Logo特别丑!!!忍不了!!!),...