python杀线程_python-有什么办法可以杀死线程吗?
小编典典
在Python和任何语言中,突然终止线程通常都是一种糟糕的模式。请考虑以下情况:
线程持有必须正确关闭的关键资源
该线程创建了其他几个必须同时终止的线程。
如果你负担得起的话(如果你要管理自己的线程),处理此问题的一种好方法是有一个exit_request标志,每个线程定期检查一次,以查看是否该退出。
例如:
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
在此代码中,你应stop()在希望退出线程时调用它,然后使用来等待线程正确退出join()。线程应定期检查停止标志。
但是,在某些情况下,你确实需要杀死线程。一个示例是当你包装一个忙于长时间调用的外部库并且想要中断它时。
以下代码允许(有一些限制)在Python线程中引发Exception:
def _async_raise(tid, exctype):
'''Raises an exception in the threads with id tid'''
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(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(ctypes.c_long(tid), None)
raise SystemError("PyThreadState_SetAsyncExc failed")
class ThreadWithExc(threading.Thread):
'''A thread class that supports raising exception in the thread from
another thread.
'''
def _get_my_tid(self):
"""determines this (self's) thread id
CAREFUL : this function is executed in the context of the caller
thread, to get the identity of the thread represented by this
instance.
"""
if not self.isAlive():
raise threading.ThreadError("the thread is not active")
# do we have it cached?
if hasattr(self, "_thread_id"):
return self._thread_id
# no, look for it in the _active dict
for tid, tobj in threading._active.items():
if tobj is self:
self._thread_id = tid
return tid
# TODO: in python 2.6, there's a simpler way to do : self.ident
raise AssertionError("could not determine the thread's id")
def raiseExc(self, exctype):
"""Raises the given exception type in the context of this thread.
If the thread is busy in a system call (time.sleep(),
socket.accept(), ...), the exception is simply ignored.
If you are sure that your exception should terminate the thread,
one way to ensure that it works is:
t = ThreadWithExc( ... )
...
t.raiseExc( SomeException )
while t.isAlive():
time.sleep( 0.1 )
t.raiseExc( SomeException )
If the exception is to be caught by the thread, you need a way to
check that your thread has caught it.
CAREFUL : this function is executed in the context of the
caller thread, to raise an excpetion in the context of the
thread represented by this instance.
"""
_async_raise( self._get_my_tid(), exctype )
(基于Tomer Filiba的Killable Threads。有关return值的引用PyThreadState_SetAsyncExc似乎来自旧版本的Python。)
如文档中所述,这不是灵丹妙药,因为如果线程在Python解释器之外很忙,它将无法捕获中断。
此代码的一个很好的用法模式是让线程捕获特定的异常并执行清理。这样,你可以中断任务并仍然进行适当的清理。
2020-02-04
python杀线程_python-有什么办法可以杀死线程吗?相关推荐
- python多线程调度_python并发编程之进程、线程、协程的调度原理(六)
进程.线程和协程的调度和运行原理总结. 系列文章 进程.线程的调度策略介绍 linux中的进程主要有三种调度策略: 优先级调度:将进程分为普通进程和实时进程: 先进先出(队列)调度:实时进程先创建的先 ...
- python获取电脑几核几线程_python编程测试电脑开启最大线程数实例代码
本文实例代码主要实现python编程测试电脑开启最大线程数,具体实现代码如下. #!/usr/bin/env python #coding=gbk import threading import ti ...
- python求股票收益率_python – 有没有办法自动获取许多股票的一般信息,如市盈率,收益率等等?...
历史将是困难的. R的 quantmod软件包有getQuote,它与yahooQF一起是获取当前值所需的全部内容. require("quantmod") getQuote(&q ...
- python结束线程_python终止线程
可以通过以下方式来终止线程:通过抛出异常来终止进程 通过一个终止标志来终止进程 使用traces来终止进程 使用多线程模型来终止进程 通过将进程设置为deamon来终止进程 使用隐藏属性_stop() ...
- tomcat关闭后线程依然运行解决办法
tomcat关闭后线程依然运行解决办法,设置线程为守护线程 守护线程与非守护线程 最近在看多线程的Timer章节,发现运用到了守护线程,感觉Java的基础知识还是需要补充. Java分为两种线程:用户 ...
- python杀死线程的方法_python杀死一个线程的方法
由于python线程没有提供abort方法,所以我们需要自己想办法解决此问题,面对这一问题,小编帮大家解决phthon杀死一个线程的方法 最近在项目中遇到这一需求: 我需要一个函数工作,比如远程连接一 ...
- python锁机制_Python并发编程之谈谈线程中的“锁机制”(三)
大家好,并发编程 进入第三篇. 今天我们来讲讲,线程里的锁机制. 本文目录 何为Lock( 锁 )?如何使用Lock( 锁 )?为何要使用锁?可重入锁(RLock)防止死锁的加锁机制饱受争议的GIL( ...
- python协程和线程_python之并发编程(线程\进程\协程)
一.进程和线程 1.进程 假如有两个程序A和B,程序A在执行到一半的过程中,需要读取大量的数据输入(I/O操作),而此时CPU只能静静地等待任务A读取完数据才能继续执行,这样就白白浪费了CPU资源.是 ...
- python apply_async死锁_python之并发编程(线程\进程\协程)
一.进程和线程 1.进程假如有两个程序A和B,程序A在执行到一半的过程中,需要读取大量的数据输入(I/O操作),而此时CPU只能静静地等待任务A读取完数据才能继续执行,这样就白白浪费了CPU资源.是不 ...
最新文章
- 关于大型网站技术演进的思考(四)-存储的瓶颈4
- CSS 负边距自适应布局
- 单元测试命名最佳实践[关闭]
- LPTSTR、LPCSTR、LPCTSTR、LPSTR的含义
- 基于SSD的Kafka应用层缓存架构设计与实现
- 光驱怎么挂载第二个光驱_重装系统下侦测不到光驱怎么解决?
- hdb3编码规则波形_光电编码器都归入8543吗?
- 设计模式一网打尽,40余篇文章带你领略设计模式之美
- 2020武大计算机学院研究生补录通知,2020年武汉大学硕士研究生复试录取工作细则汇总...
- 计算机WORD列宽行高怎么设置,高会《职称计算机》Word 2007:设置行高和列宽
- NameNode DataNode
- 廖雪峰Python学习
- git官网下载速度太慢解决方法
- android 百度地图应用
- Android逆向之分析某锁机恶意软件
- YOLO输出位置信息
- [Obsidian]懒人必备插件附使用教程
- ubuntu16.04下,man: nothing appropriate.问题解决
- 简单谈谈STM32(一) - 走近嵌入式
- “中国探月工程”,“长征三号火箭”,“月球车”,英语怎么说?
热门文章
- log4net 使用手记
- HTTP Status 400,400 (Bad Request)
- JDBC学习笔记(查询SQL语句得到的结果对象)
- kettle mysql 乱码
- bugscan泄露代码解密
- rendering omni shadow in one pass.
- 【数据结构】——排序二叉树
- GitHub上传文件的过滤规则 -- windows下
- 基于Spring Security的认证方式_Spring Security 的结构总览_Spring Security OAuth2.0认证授权---springcloud工作笔记122
- 微服务升级_SpringCloud Alibaba工作笔记0023---Nacos之Namespace空间方案