一 .进程(Pipe 双管道通信)
1.进程管道概念(Pipe)
管道: 是python多进程中一种交换数据的方式
multiprocessing.Pipe()则可以双向通信
2.管道使用(Pipe)
from multiprocessing import Pipe
from multiprocessing import Process
conn1,conn2=Pipe() conn1.send("你好哈哈哈") print(conn2.recv()) # 你好哈哈哈
进程之间通信 方法1
def show (conn1): print("子进程")# 子进程 conn1.send("你好呀哈哈哈哈哈哈哈") if __name__ == ‘__main__‘: print("主进程!!!!!!!!!!!!") conn1,coon2=Pipe() p1= Process(target=show,args=(conn1,)) p1.start() print(coon2.recv()) # 你好呀哈哈哈哈哈哈哈 # 执行顺序 # 主进程!!!!!!!!!!!! # 子进程 # 你好呀哈哈哈哈哈哈哈
进程之间通信 方法2
def show (conn2): print("子进程") # 子进程 aa=conn2.recv() print(aa) # 你好世界!!!!!! if __name__ == ‘__main__‘: print("主进程!!!!!!!!!!!!") conn1,coon2=Pipe() conn1.send("你好世界!!!!!!") p1= Process(target=show,args=(coon2,)) p1.start() # 执行顺序 # 主进程!!!!!!!!!!!! # 子进程 # 你好世界!!!!!!
进程之间通信 方法3
def show (conn1): while True: msg=conn1.recv() if msg is None:break # 如果没有明确条件 就会阻塞到这里(死循环) 程序就结束不了 print(msg) if __name__ == ‘__main__‘: print("主进程!!!!!!!!!!!!") conn1,coon2=Pipe() p1= Process(target=show,args=(conn1,)) p1.start() for i in range(10): coon2.send("你好鸭阿嘎嘎嘎") coon2.send(None) # 如果没有明确条件 就会阻塞到这里(死循环) 执行结果: 主进程!!!!!!!!!!!! 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 进程已结束,退出代码 0
# 进程之间通信方法四
def show (conn1,coon2):#一个发送 conn2 一个接收 conn1 coon2.close() while True: try: msg=conn1.recv() print(msg) except EOFError: conn1.close() break if __name__ == ‘__main__‘: print("主进程!!!!!!!!!!!!") conn1,conn2=Pipe() # 可以把这两个对象传给子进程 一个发送 conn2 一个接收 conn1 p1= Process(target=show,args=(conn1,conn2)) p1.start() conn1.close() for i in range(10): conn2.send("你好鸭阿嘎嘎嘎") conn2.close() 执行结果: 主进程!!!!!!!!!!!! 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 你好鸭阿嘎嘎嘎 进程已结束,退出代码 0
图文说明
3.使用管道来实现生产者消费者(Pipe)
原文:https://www.cnblogs.com/Sup-to/p/11194096.html