[英]Is there a canonical way of terminating a thread in python?
我想在python中强制终止线程:我不想设置一个事件并等待线程检查它并退出。 我正在寻找像kill -9
这样的简单解决方案。 如果没有像私人方法等操作那样的肮脏黑客,这是否可以做到这一点?
如果你不介意你的代码运行速度慢十倍,你可以使用下面实现的Thread2
类。 下面的示例显示了调用新的stop
方法应该如何杀死下一个字节码指令上的线程。
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%。
线程在它们结束时结束。
您可以发信号通知您希望它尽快终止的线程,但是它假定在线程中运行的代码的协作,并且它不会在发生这种情况时提供上限保证。
一种经典的方法是使用类似exit_immediately = False
的变量,并让线程的主例程定期检查它并在值为True
终止。 要让线程退出,请设置exit_immediately = True
并在所有线程上调用.join()
。 显然,这只适用于线程能够定期检查的情况。
如果您想要的是能够让程序终止而不关心某些线程会发生什么,那么您想要的是daemon
线程。
来自文档 :
当没有剩下活着的非守护程序线程时,整个Python程序退出。
用法程序示例:
import threading
import time
def test():
while True:
print "hey"
time.sleep(1)
t = threading.Thread(target=test)
t.daemon = True # <-- set to False and the program will not terminate
t.start()
time.sleep(10)
琐事: daemon
线程在.Net中称为background
线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.