Python--day38---进程间通信--初识队列(multiprocess.Queue)之生产者,消费者模型

1,生产者消费者模型.py

 1 import random
 2 import time
 3 from multiprocessing import Queue, Process
 4 
 5 def producer(name,food,q):
 6     for i in range(4):
 7         time.sleep(random.randint(1,3))
 8         f = '%s生产了%s%s'%(name,food,i)
 9         print(f)
10         q.put(f)
11 
12 def consumer(q,name):
13     while True:
14         food = q.get()
15         if food is None:
16             print('%s获取到了一个空',name)
17             break
18         print('\033[31m%s消费了%s\033[0m' %(name,food))
19         time.sleep(random.randint(1,3))
20 
21 if __name__ == '__main__':
22     q = Queue(20)
23     p1 = Process(target=producer,args=('Egon','包子',q))
24     p2 = Process(target=producer,args=('wusir','泔水',q))
25     c1 = Process(target=consumer,args=(q,'alex'))
26     c2 = Process(target=consumer,args=(q,'jinboss'))
27     p1.start()
28     p2.start()
29     c1.start()
30     c2.start()
31     p1.join()
32     p2.join()
33     q.put(None)

运行结果:

 

posted @ 2019-01-27 12:15  莱茵河的雨季  阅读(323)  评论(0编辑  收藏  举报