【发布时间】:2019-01-29 01:07:09
【问题描述】:
我有这个线程在后台运行,可以从主线程更新:
import threading
from Queue import Queue
from time import sleep
class Animation(threading.Thread):
SIGNAL_STOP = 'stop'
def __init__(self, framerate):
threading.Thread.__init__(self)
self.queue = Queue()
self.framerate = framerate
def tell(self, data):
self.queue.put(data)
def stop(self):
self.tell(Animation.SIGNAL_STOP)
def loop(self):
# Override this method to implement animation loop
pass
def update(self, data):
# Override this method to implement the state update
pass
def cleanup(self):
# Override this method to implement what's done when the animation is stopped
pass
def run(self):
while True:
if not self.queue.empty():
data = self.queue.get()
if data == Animation.SIGNAL_STOP:
break;
self.update(data)
self.loop()
sleep(1. / self.framerate)
self.cleanup()
class TestAnimation(Animation):
def __init__(self, framerate):
super(TestAnimation, self).__init__(framerate)
self.num = 0
def loop(self):
print 'num =', self.num
self.num = self.num + 1
def update(self, data):
print 'update:', data
def cleanup(self):
print 'graceful exit'
print 'start'
ta = TestAnimation(1)
ta.start()
sleep(3)
ta.update(123)
sleep(3)
#ta.stop() # I'd like the animation thread to feel that the parent wants to exit and carry out stopping itself
print 'end'
exit()
我想实现一些方法来检测父线程何时想要退出,然后所有正在运行的线程都会优雅地终止自己。我更喜欢这样,而不是显式调用正在运行的线程的 stop() 方法。
【问题讨论】:
标签: python multithreading