有什么方法可以杀死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):
super(StoppableThread, self).__init__()
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
在这段代码中,当你想要退出时,你应该在线程上调用stop(),然后等待线程使用join()正确退出。 线程应定期检查停止标志。
但是有些情况下,你真的需要杀死一个线程。 一个例子就是当你打包一个长时间调用的外部库并且你想中断它时。
以下代码允许(有一些限制)在Python线程中引发异常:
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(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, 0)
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 )
正如文档中指出的那样,这不是一个神奇的项目,因为如果线程在Python解释器之外忙碌,它不会捕获中断。
此代码的一个很好的使用模式是让线程捕获特定的异常并执行清理。 这样,您可以中断任务并仍然进行适当的清理。
没有官方的API来做这件事,不。
您需要使用平台API来终止线程,例如pthread_kill或TerminateThread。 您可以通过pythonwin或ctypes访问此类API。
请注意,这本质上是不安全的。 它可能会导致无法收集的垃圾(来自堆栈框架的局部变量变成垃圾),并且如果被杀死的线程在被杀死的时候具有GIL,则可能导致死锁。
一个multiprocessing.Process
可以p.terminate()
在我想杀死一个线程但不想使用flags / locks / signals / semaphores / events / whatever的情况下,我将这些线程提升为完整的进程。 对于只使用几个线程的代码,开销并不是那么糟糕。
例如,这可以方便地终止执行阻塞I / O的助手“线程”
转换是微不足道的:在相关的代码中,将所有threading.Thread
替换为multiprocessing.Process
并将所有queue.Queue
为multiprocessing.Queue
,并将所需的p.terminate()
调用添加到您的父进程中,该父进程想要p.terminate()
其子p
Python文档
链接地址: http://www.djcxy.com/p/9647.html上一篇: Is there any way to kill a Thread in Python?
下一篇: Quiscence search implementation for two player board game