Python 消除线程困境
我找到了两种方法来实现我的Python 消除线程困境,python,multithreading,Python,Multithreading,我找到了两种方法来实现我的terminateablethread类。 我想问一下你对其中每一项的利弊或看法,有什么不同吗 第一种解决方案:使用线程类的\u stop()私有方法: class TerminatableThread(threading.Thread): def __init__(self, *args, **argv): threading.Thread.__init__(self, *args, **argv) def terminate(sel
terminateablethread
类。
我想问一下你对其中每一项的利弊或看法,有什么不同吗
第一种解决方案:使用线程类的\u stop()
私有方法:
class TerminatableThread(threading.Thread):
def __init__(self, *args, **argv):
threading.Thread.__init__(self, *args, **argv)
def terminate(self):
threading.Thread._Thread__stop(self) #@UndefinedVariable
@property
def should_run(self):
return threading.Thread.is_alive(self)
第二种解决方案:使用附加的事件
:
class TerminatableThread(threading.Thread):
def __init__(self, *args, **argv):
self.__terminated = threading.Event()
threading.Thread.__init__(self, *args, **argv)
def terminate(self):
self.__terminated.set()
@property
def should_run(self):
return not self.__terminated.is_set()
你觉得怎么样?
感谢第一种解决方案:您不应该使用私有方法,因为这种方法可能会发生变化,而且形式也不好。另外,一根线也不应该冷停;您应该让线程内的进程有机会首先进行清理,并自行响应终止请求
第二种解决方案是:与Java等其他语言相比,Python上的抽象类不太常见,也不太必要。如果terminateablethread
本身就是线程操作的抽象类,为什么不直接向其添加terminated
行为
class TerminatableThread(threading.Thread):
def __init__(self, *args, **argv):
super.__init__(self, *args, **argv)
self.terminated = False
# Note: not actually thread-safe
def terminate(self):
self.terminated = True
编辑:您删除了“抽象类”建议,但我会使用某种线程安全标志机制。线程事件听起来可能会这样做,所以我会选择这个选项。Python线程也可以使用sys.exit()关闭,sys.exit()在线程中与thread.exit()相同
我认为你不应该虐待线程。他们的生命已经够糟糕的了,因为这里只有一种终止线程的好方法——除非你是一个操作系统并且终止了整个进程,否则你不应该尝试它,除非是在最需要的情况下。谢谢。这很有趣。我认为我为事件
对象提供了正确的线程安全方式。我知道线程不应该被综合终止,但是你有没有想过为什么会有这种停止方法?您不能以任何其他方式使用它。大多数线程机制提供一些低级方式来终止它们。但是_______________________________________。当工作线程完成时,它可以在内部用于停止操作系统线程。另见:
def nuke(self):
# set autodestruct, remove thread from stack and exit thread
global threads
try:
threads.remove([self.threadId,self])
except:
sys.exit()