以下环境都是windows7 python3.5环境,模拟洗衣、烘干的队列过程
《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《
先使用单独的进程来模拟:
1、启动redis服务器
2、命令行运行dry客户端:
python redis_dryer.py
其内容如下(不懂可以留言):
import redis
conn = redis.Redis()
print('Dryer is starting')
while True:
msg = conn.blpop('dishes')
if not msg:
break
val = msg[1].decode('utf-8')
if val == 'quit':
break
print('Dried', val)
print('Dishes are dried')
python redis_washer.py
其内容如下:
import redis
conn = redis.Redis()
print('Washer is starting')
dishes = ['salad', 'bread', 'entree', 'dessert']
for dish in dishes:
msg = dish.encode('utf-8')
conn.rpush('dishes', msg)
print('Washed', dish)
conn.rpush('dishes', 'quit')
print('Washer is done')
4、两个客户端会交替打印出信息,模拟成功(不贴图了,麻烦)下面使用多线程来模拟这个队列:
1、启动redis服务器
2、命令行运行dry客户端:
python redis_dryer2.py
其内容如下(不懂可以留言):
def dryer():
import redis
import os
import time
conn = redis.Redis()
pid = os.getpid()
timeout = 20
print('Dryer process %s is starting' % pid)
while True:
msg = conn.blpop('dishes', timeout)
if not msg:
break
val = msg[1].decode('utf-8')
if val == 'quit':
break
print('%s: dried %s' % (pid, val))
time.sleep(0.1)
print('Dryer process %s is done' % pid)
import multiprocessing
DRYERS=3
if __name__ == '__main__':
for num in range(DRYERS):
p = multiprocessing.Process(target=dryer)
p.start()
3、新命令行运行wash客户端:
python redis_washer.py
其内容同上
4、两个客户端会打印出信息如下:
wash客户端:
dry客户端:
至此,利用redis服务器模拟多线程队列完成