管道的作用- 两个进程间传递消息
from multiprocessing import Pipe, Process def func(conn1,conn2): conn2.close() #子进程只需使用connection1,故关闭connection2 while True: try: msg = conn1.recv() print(msg) except EOFError: #没收数据接收的时候,才抛出的异常 conn1.close() break if __name__ == '__main__': conn1,conn2 = Pipe()#建立一个管道,管道返回两个connection Process(target=func, args=(conn1,conn2)).start() conn1.close() #主进程只需要一个connection,故关闭一个 for i in range(20): conn2.send('吃了吗') #主进程发送 conn2.close() #主进程关闭connection2
管道是进程数据不安全的
- pipe有数据不安全性 - 多个消费者同时取一个数据的情况可能发送
- 通过IPC通讯
- 解决方法 -加锁
- 队列是进程数据安全的-队列是基于管道加锁
from multiprocessing import Process,Pipe,Lock def consumer(p,name,lock): produce, consume=p produce.close() while True: lock.acquire() baozi=consume.recv() lock.release() if baozi: print('%s 收到包子:%s' %(name,baozi)) else: consume.close() break def producer(p,n): produce, consume=p consume.close() for i in range(n): produce.send(i) produce.send(None) produce.send(None) produce.close() if __name__ == '__main__': produce,consume=Pipe() lock = Lock() c1=Process(target=consumer,args=((produce,consume),'c1',lock)) c2=Process(target=consumer,args=((produce,consume),'c2',lock)) p1=Process(target=producer,args=((produce,consume),10)) c1.start() c2.start() p1.start() produce.close() consume.close() c1.join() c2.join() p1.join() print('主进程')
来源:https://www.cnblogs.com/konglinqingfeng/p/9696484.html