是否有终止python中线程的规范方法? [英] Is there a canonical way of terminating a thread in python?
问题描述
我想在python中强制终止线程:我不想设置事件并等待线程检查并退出.我正在寻找像kill -9
这样的简单解决方案.这样做有没有像使用私有方法等那样肮脏的技巧?
I want to force threads termination in python: I don't want to set an event and wait until the thread checks it and exits. I'm looking for a simple solution like kill -9
. Is this possible to do that without dirty hacks like operating with private methods etc.?
推荐答案
如果您不介意代码运行速度慢大约十倍,则可以使用下面实现的Thread2
类.下面的示例显示了如何调用新的stop
方法如何杀死下一条字节码指令上的线程.
If you do not mind your code running about ten times slower, you can use the Thread2
class implemented below. An example follows that shows how calling the new stop
method should kill the thread on the next bytecode instruction.
import threading
import sys
class StopThread(StopIteration): pass
threading.SystemExit = SystemExit, StopThread
class Thread2(threading.Thread):
def stop(self):
self.__stop = True
def _bootstrap(self):
if threading._trace_hook is not None:
raise ValueError('Cannot run thread with tracing!')
self.__stop = False
sys.settrace(self.__trace)
super()._bootstrap()
def __trace(self, frame, event, arg):
if self.__stop:
raise StopThread()
return self.__trace
class Thread3(threading.Thread):
def _bootstrap(self, stop_thread=False):
def stop():
nonlocal stop_thread
stop_thread = True
self.stop = stop
def tracer(*_):
if stop_thread:
raise StopThread()
return tracer
sys.settrace(tracer)
super()._bootstrap()
################################################################################
import time
def main():
test = Thread2(target=printer)
test.start()
time.sleep(1)
test.stop()
test.join()
def printer():
while True:
print(time.time() % 1)
time.sleep(0.1)
if __name__ == '__main__':
main()
Thread3
类的运行代码似乎比Thread2
类快33%.
The Thread3
class appears to run code approximately 33% faster than the Thread2
class.
这篇关于是否有终止python中线程的规范方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!