Python的Threadped.Thread的StoppableThread子类的示例用法

时间:2016-11-02 14:23:19

标签: python

我试图了解在Python中杀死线程问题的高度推崇的解决方案:here。作者提供了一个类stop(),并用文字描述了如何使用它(即通过调用其join()方法并等待线程使用import time import threading class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self, *args, **kwargs): super(StoppableThread, self).__init__(*args, **kwargs) self._stop = threading.Event() def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() def run_forever(): while True: print("Hello, world!") time.sleep(1) thread = StoppableThread(target=run_forever) thread.start() time.sleep(5) thread.stop() thread.join() 正确退出。)

我尝试使用一个简单的例子来完成这项工作:

Hello, world!

我希望程序在thread停止前大约打印StoppableThread 5次。但是,我观察到它只是无限期地继续打印。

有人可以澄清enum Object: Int{ case House1 = 0 case House2 = 1 var description: String { return descriptor } var descriptor:String{ switch self{ case .House1: return "Cottage" case .House2: return "House" } } static func valueFor(string:String) -> Int{ switch string{ case "Cottage": return 0 case "House": return 1 default: return 2 } } } let obj = Object.House1 print(obj.description) print(obj.rawValue) print(Object.valueFor(string: "Cottage") //Output Cottage 0 0 子类的正确用法吗?

1 个答案:

答案 0 :(得分:1)

问题以红色标注。您不检查while循环是否发生stopped()条件。您只能使用它来发送"消息"它现在应该退出的线程,但它不会自动执行。

您应该在while循环中添加if子句,并在检测到停止条件时退出。

这样做,它应该有效:

import time
import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stop = threading.Event()

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

    def stopped(self):
        return self._stop.isSet()

    def run(self):
        while True:
            if self.stopped():
                return
            print("Hello, world!")
            time.sleep(1)

thread = StoppableThread()

thread.start()
time.sleep(5)
thread.stop()
thread.join()

或者您可以继承StoppableThread:

import time
import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self, *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stop = threading.Event()

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

    def stopped(self):
        return self._stop.isSet()


class pup(StoppableThread):
    def __init__(self, *args, **kwargs):
        super(pup, self).__init__(*args, **kwargs)

    def run(self):
        while True:
            if self.stopped():
                return
            print("Hello, world!")
            time.sleep(1)

thread = pup()

thread.start()
time.sleep(5)
thread.stop()

thread.join()

如果你的线程有效,然后睡觉,并且循环直到令人作呕,这不是一个非常好的方法,因为它在睡觉时不会检测到这种情况。如果你在线程中长时间睡眠,它们需要在线程退出之前到期。

我在这些情况下使用了队列。在启动线程之前,我创建了一个队列并将其作为参数传递给线程。我用Queue.get(True,30)替换睡眠(30),睡眠时间为30秒或者直到有消息。然后,如果我需要更深入地与线程通信,我可以对此消息采取行动,关闭或执行其他操作。

哈努哈利