停止python中的线程,为什么以下操作不起作用?

停止python中的线程,为什么以下操作不起作用?,python,multithreading,Python,Multithreading,我一直在尝试提供阻止线程跟随的功能。我有以下课程: class WorkerThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self, id): super(WorkerThread, self).__in

我一直在尝试提供阻止线程跟随的功能。我有以下课程:

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

    def __init__(self, id):
        super(WorkerThread, self).__init__()
        self._id = id
        self._stop = threading.Event()

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

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

    def run(self):
        while not self.stopped():
            print ("Thread with id {0} Running".format(self._id))
            time.sleep(1)
当我创建10个线程并试图停止它们时,没有一个线程停止并继续打印

threads = [WorkerThread(x) for x in range(10)]
[thread.start() for thread in threads]
time.sleep(2) #wait
[thread.stop() for thread in threads]
[thread.join() for thread in threads]
print "All done" #never printed

有人能解释为什么停止事件被忽略吗?我还尝试使用
\u stop
属性作为标志,并在
\u init\u
中将其设置为false,在
stop()
中将其设置为True,但运气不佳。

超级(StoppableThread,self)。\u init\u init()
:StoppableThread是打字错误吗?@Emilvanov感谢您指出这一点!我编辑了原始帖子。在Linux x86-64上使用Python 2.7.6也可以。除了“seld.\u id”的拼写错误之外,我也可以。mlk我在帖子中修复了这个问题,但我认为原始代码没有拼写错误。