首页 > 编程语言 > 详细

python生产者和消费者模式实现(二)多进程方式

时间:2019-11-01 14:39:35      阅读:179      评论:0      收藏:0      [点我收藏+]
import time
import random
from multiprocessing import Process, Queue


# 生产者
def producer(q, i):
food = ‘Spam-%d‘ % i
time.sleep(random.uniform(2, 5))
timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(‘时间:%s\t生产者:%d 生产了 %d‘ % (timeVal, i, i))
q.put(food)

# 消费者
def consumer(q, i):
while True:
food = q.get()
if not food:break
time.sleep(random.uniform(1, 2))
timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(‘时间:%s\t消费者: %d\t吃了 %s‘ % (timeVal, i, food))


if __name__ == ‘__main__‘:
q = Queue()

producerPs = []
for n in range(1, 16):
producerPs.append(Process(target=producer, args=(q, n)))

for producerP in producerPs:
producerP.start()

consumerPs = []
for n in range(1, 6):
consumerPs.append(Process(target=consumer, args=(q, n)))

for consumerP in consumerPs:
consumerP.start()

for producerP in producerPs:
producerP.join()

for consumerP in consumerPs:
q.put(None)

for consumerP in consumerPs:
consumerP.join()

print(‘end‘)


python生产者和消费者模式实现(二)多进程方式

原文:https://www.cnblogs.com/WebLinuxStudy/p/11776767.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!