我实现了一个Redis包装类,如下所示。在
import redis
import threading
import time
class IntervalRedis(object):
@classmethod
def init(cls, interval=0.1, host='localhost', port=6379, db=0):
cls._r = redis.Redis(host=host, port=port, db=db)
cls.r = cls._r.pipeline()
cls.t = threading.Thread(target=cls._intervalExecute)
cls.interval = interval
cls.t.start()
@classmethod
def _intervalExecute(cls):
while True:
print "1"
cls.r.execute() # blocked at here after some loop cycle.
print "2"
time.sleep(cls.interval)
print "3"
if __name__ == "__main__":
print "start"
IntervalRedis.init()
count = 0
while True:
count+=1
IntervalRedis.r.lpush("foo", count)
time.sleep(0.01)
if count == 10000000:
break;
print "end"
在main语句中,它访问redis pipline object
并运行lpush
命令,循环while
语句。在
但是命令的真正执行是在_intervalExecute
中以pipline execute()
的规则间隔运行。在
我认为它必须在count
达到10000000时运行。在
但是,当我运行这段代码时,它会在循环周期后被阻塞。 (有时3个周期,有时5个周期随机)
你能推荐我吗?在
从不同的线程访问同一个Redis连接是不安全的。每个线程都应该有自己的连接来使用(或者使用一个连接池)。在
在您的示例中,有两个线程共享同一管道和连接。在
相关问题 更多 >
编程相关推荐