103-python-进程-管道( 生产者消费者模型例子 )
import time import random from multiprocessing import Process,Pipe,Lock def producer(con,pro,name,food): con.close() for i in range(8): time.sleep(random.random()) msg = '%s 生产的%s %s个'%(name,food,i) pro.send(msg) pro.close() def consumer(con,pro,name,lock): pro .close() while True: try: # lock.acquire() ret = con.recv() # lock.release() print('%s 消费了 %s' % (name, ret)) time.sleep(random.random()) except EOFError: con.close() break if __name__ == '__main__': lock = Lock() con,pro = Pipe() p1 = Process(target=producer,args=(con,pro,'goblin','app')) p1.start() c1 = Process(target=consumer,args=(con,pro,'monster',lock)) c1.start() c2 = Process(target=consumer, args=(con, pro, 'pig',lock)) c2.start() con.close() pro.close()