我一直在努力提供阻止this thread 之后的线程的功能。我有以下课程:
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
有人可以解释为什么忽略停止事件?我还尝试将_stop
属性用作标记,并在__init__
和True
stop()
中将其设置为false,但没有运气。