杀了一条线迪勒姆

2024-10-03 19:23:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我找到了两种实现TerminatableThread类的方法。 我想问一下你对每一个的利弊或意见,有什么不同吗?在

第一个解决方案:使用__stop()类的__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)

第二种解决方案:使用额外的Event

^{pr2}$

你觉得怎么样? 谢谢


Tags: 方法selfinitdefargs解决方案threadclass
2条回答

Python线程也可以用系统出口()在一个线程内与线程退出()

def nuke(self):
    # set autodestruct, remove thread from stack and exit thread
    global threads
    try:
        threads.remove([self.threadId,self])
    except:
        sys.exit()

对于第一个解决方案:你不应该使用私有方法,因为它可以改变,而且无论如何都是不好的形式。另外,线程不应该冷停;应该给线程内的进程一个先清理的机会,然后自己响应终止请求。在

对于第二种解决方案:抽象类在Python上的通用性和必要性都不如Java等其他语言。如果您的TerminatableThread本身就是线程操作的抽象类,为什么不直接向它添加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

编辑:您删除了“抽象类”建议,但我将使用某种线程安全标志机制。线程事件听起来可能会这样做,所以我将使用该选项。在

相关问题 更多 >