管道是进程数据不安全的(进程争抢数据),解决办法-加锁
队列=管道+锁
import time
import random
from multiprocessing import Process,Pipe,Lock
def consumer(name,lock,p_pipe,c_pipe):
p_pipe.close()
while True:
lock.acquire()
food = c_pipe.recv()
lock.release()
if food:
print('%s吃了%s'%(name,food))
time.sleep(random.randint(1,3))
else:
c_pipe.close()
break
def producer(name,food,p_pipe,c_pipe):
c_pipe.close()
for i in range(4):
time.sleep(random.randint(1,3))
print('%s生产了%s%s'%(name,food,i))
p_pipe.send(food)
p_pipe.send(None)
p_pipe.send(None)
p_pipe.close()
if __name__ == '__main__':
p_pipe,c_pipe = Pipe()
l = Lock()
p1 = Process(target=producer,args=('汤姆','包子',p_pipe,c_pipe))
c1 = Process(target=consumer,args=('狗狗',l,p_pipe,c_pipe))
c2 = Process(target=consumer, args=('小鸟',l,p_pipe,c_pipe))
p1.start()
c1.start()
c2.start()
p_pipe.close()
c_pipe.close()