首页 > 系统服务 > 详细

九. 并发编程 (进程管道)

时间:2019-07-16 13:03:08      阅读:100      评论:0      收藏:0      [点我收藏+]

一 .进程(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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!