创建一个在设置自己的停止标志时停止的线程

时间:2017-10-24 22:46:32

标签: python multithreading

import threading
import time

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""
    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

    def func(self):
        while True:
            time.sleep(0.5)
            print("Hi")
            if self.stopped():
                break

t = StoppableThread()
t.target = t.func
t.start()
time.sleep(10)
t.stop()

这是我尝试创建一个可停止的线程,它将运行自己的方法,直到它停止,此时它应该终止(while中的func循环被打破) 。不幸的是,此代码不会打印任何内容。我的愿望是"Hi"每0.5秒打印一次,持续10秒。

我还尝试将方法定义为外部函数,并将线程作为参数传递:

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""
    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

def func(thread):
    while True:
        time.sleep(0.5)
        print("Hi")
        if thread.stopped():
            break

t = StoppableThread()
t.target = func
t.args = (t,) # passing in the thread as an argument to func so that func can check the stopped()-flag
t.start()
time.sleep(10)
t.stop()

此代码产生与第一个示例相同的结果。这有什么不对?我怎样才能让它发挥作用?

2 个答案:

答案 0 :(得分:1)

在@ user2357112提示的帮助下,我设法提出了这个解决方案(覆盖run()):

import threading
import time

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""
    def __init__(self):
        super(StoppableThread, self).__init__()
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

    def run(self):
        self.func()

    def func(self):
        while True:
            time.sleep(0.5)
            print("Hi")
            if self.stopped():
                break

t = StoppableThread()
t.start()
time.sleep(10)
t.stop()

如果有人能解释的话,我仍然想知道如何用闭包来做这件事。

答案 1 :(得分:0)

您的两个示例都通过执行t.target = func来设置线程的目标,这是指定目标的错误方法。您需要将target = func传递给构造函数,然后将其传递给对super

的调用

你要做的第一个案例super(StoppableThread, self).__init__(target = self.func)和你要做的第二个案例

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""
    def __init__(self, target): 
        self._stop_event = threading.Event()
        super(StoppableThread, self).__init__(target = target, args=(self._stop_event,))

然后t = StoppableThread(target = func)将正常工作。