python中是否有终止线程的标准方法?
我想在python中强制线程终止:我不想设置事件并等待线程检查并退出。我正在寻找一个简单的解决方案,比如python中是否有终止线程的标准方法?,python,multithreading,Python,Multithreading,我想在python中强制线程终止:我不想设置事件并等待线程检查并退出。我正在寻找一个简单的解决方案,比如kill-9。如果没有像使用私有方法等肮脏的黑客行为,这有可能做到吗?线程在这样做时结束 您可以向一个线程发出信号,表示希望它尽快终止,但这假设了线程中运行的代码的协作,并且它不提供发生这种情况的上限保证 一种经典的方法是使用变量,如exit\u instally=False,让线程的主例程定期检查它,如果值为True,则终止。要让线程退出,可以设置exit\u立即=True并在所有线程上调用
kill-9
。如果没有像使用私有方法等肮脏的黑客行为,这有可能做到吗?线程在这样做时结束
您可以向一个线程发出信号,表示希望它尽快终止,但这假设了线程中运行的代码的协作,并且它不提供发生这种情况的上限保证
一种经典的方法是使用变量,如
exit\u instally=False
,让线程的主例程定期检查它,如果值为True
,则终止。要让线程退出,可以设置exit\u立即=True
并在所有线程上调用.join()
。显然,这只有在线程能够定期检入时才起作用。如果您想要的只是能够让程序在结束时终止,而不关心某些线程发生了什么,那么您需要的是守护进程线程
从:
当没有激活的非守护进程线程时,整个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)
导入线程
导入时间
def test():
尽管如此:
打印“嘿”
时间。睡眠(1)
t=线程。线程(目标=测试)
t、 daemon=True#如果您不介意代码运行速度慢十倍,那么可以使用下面实现的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%。不,不是。不支持从线程外部终止线程的方法。原因是无法知道线程可能锁定了哪些资源。编写正确程序的唯一方法是让线程在他们自己知道结束是安全的情况下结束。@NedBatchelder我想你是对的,但希望得到一些批准,比如一个语言规范等。stdlib中缺少方法难道还不够吗?@NedBatchelder heh:-)有道理,而下面是关于Java的,这里也适用同样的推理:它类似于stop=threading.Event()
;在主线程中:stop.set()
;在应该停止的线程中:if stop.is_set():exit
但OP不想使用itI注意到,我正在寻找一种不需要代码与事件协作和其他同步的解决方案。物体。