在python3中停止线程

时间:2011-10-18 11:16:29

标签: python-3.x

我怎样才能更好地编写以下课程?例如,有一个很好的方法可以使两个标志is_alive和is_finished滑动吗?

Monitor(threading.Thread):
    def run(self):
        resource = Resource("com1")

        self.alive = True
        self.is_finished = False
        try:
            while self.alive:
                pass # use resource
        finally:
            resource.close()
            self.is_finished = True    

    def stop(self):
        self.alive = False
        while not self.is_finished:
            time.sleep(0.1)

1 个答案:

答案 0 :(得分:8)

这就是它。但是,您不需要is_finished,因为您可以使用join()方法:

Monitor(threading.Thread):
    def run(self):
        resource = Resource("com1")

        self.alive = True
        try:
            while self.alive:
                pass # use resource
        finally:
            resource.close()

    def stop(self):
        self.alive = False
        self.join()

如果您确实需要查找线程是否正在运行,可以致电mythread.is_alive() - 您无需自行设置。