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

前端之家收集整理的这篇文章主要介绍了python生产者和消费者模式实现(二)多进程方式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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,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,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相关文章