0

我找到了两种方法来实现我的TerminatableThread课程。我想问问你对他们每个人的优缺点或意见,有什么不同吗?

第一种解决方案:使用类的__stop()私有方法Thread

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

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()

你怎么看?谢谢

4

2 回答 2

0

对于第一个解决方案:您不应该使用私有方法,因为这可能会改变并且无论如何都是不好的形式。另外,线程不应该被冷停;您应该让该线程内的进程有机会首先进行清理,并自行响应终止请求。

对于第二种解决方案:抽象类在 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

编辑:您删除了“抽象类”提案,但我会使用某种线程安全标志机制。线程事件听起来他们可能会这样做,所以我会选择那个选项。

于 2012-06-18T19:34:29.627 回答
0

Python 线程也可以用 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()
于 2012-06-18T19:47:58.247 回答