import redis
import threading
class Listener(threading.Thread):
def __init__(self, r, channel):
threading.Thread.__init__(self)
self.redis = r
self.pubsub = self.redis.pubsub()
self.pubsub.subscribe(channel)
def run(self):
for item in self.pubsub.listen():
# do stuff
pass
在上面的代码中我如何停止线程?
下面我有一个示例代码向您展示我想要的内容:
class Listener(threading.Thread):
def __init__(self, r, channel):
threading.Thread.__init__(self)
self.redis = r
self.pubsub = self.redis.pubsub()
self.pubsub.subscribe(channel)
self.stop = False
def run(self):
while not stop:
# get item from channel
因此,当属性 stop == True 时,线程将退出循环并完成。那可能吗?如果不是,有什么替代方案?