python多进程之间的通信:消息队列Queue


python中进程的通信:消息队列。


我们知道进程是互相独立的,各自运行在自己独立的内存空间。
所以进程之间不共享任何变量。
我们要想进程之间互相通信,传送一些东西怎么办?
需要用到消息队列!!

进程之间通过Queue进行通信
这是一个消息队列,
q = Queue(n) 开一个能接收n条信息的队列,不传入默认动态延长

q.qsize() 返回队列中消息的条数
q.empty() 队列是否为空
q.get( block,timeout ) 取出消息,block默认为True,表示如果为空 一直等取出为止
timeout设置等多久,如果到时间还是空就抛出异常
q.get_nowait() 相当于q.get(False) 如果空 立刻抛出异常


q.put(item,block,timeout) item为向队列传送的内容
block默认为True 如果队列满了 就一直等有空位再送进去
timeout设置时间 到时间了没送进去就抛出异常
q.put_nowait(item) 相当于q.put(False) 如果满了 立即抛出异常

 1 from multiprocessing import Queue  2 if __name__ == "__main__":  3     q = Queue(3)  4     q.put("消息1")  5     q.put("消息2")  6     print(q.full())  7     q.put("消息3")  8     print(q.full())  9 
10     # 从消息队列取数据 推荐两种方法 1 捕获异常 2 判断
11 
12     try : 13         q.put("消息4",True , 2)   # 尝试写入,如果满了 2秒后抛出异常
14     except: 15         print("已经满了,现有消息%s条"%q.qsize()) 16     try : 17         q.put_nowait("消息4")   # 尝试写入 如果满了立即抛出异常
18         #相当于q.put(item,False)
19     except: 20         print("已经满了,现有消息%s条"%q.qsize()) 21 
22     if not q.full(): 23         q.put_nowait("消息4") 24 
25     if not q.empty(): 26         for i in range(q.qsize()): 27             print(q.get_nowait())

 

 

在进程池当中使用Queue 需要使用Manager().Queue()
 1 from multiprocessing  import Manager,Pool  2 import os  3 def reader(q):  4     print("我是子进程%s,我的父进程是%s,我开始读取消息"%( os.getpid(),os.getppid() ) )  5     for i in range(q.qsize()):  6         print(q.get())  7 
 8 def writer(q):  9     print("我是子进程%s,我的父进程是%s,我开始写消息"%( os.getpid(),os.getppid() )) 10     for i in "DongGe": 11  q.put(i) 12 
13 
14 if __name__ == "__main__": 15     p = Pool() 16     q = Manager().Queue() 17  p.apply(writer,(q,)) 18  p.apply(reader,(q,)) 19     #关闭进程池 不再接收任务
20  p.close() 21     #阻塞 等待进程结束,必须在close之后
22  p.join() 23 
24     print("结束")

 




免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM