41. Python Queue 多进程的消息队列 PIPE
消息队列:
消息队列是在消息传输过程中保存消息的容器。
消息队列最经典的用法就是消费者和生产者之间通过消息管道来传递消息,消费者和生产生是不通的进程。生产者往管道中写消息,消费者从管道中读消息。
相当于水管,有一个入口和出口,水从入口流入出口流出,这就是一个消息队列
线程或进程往队列里面添加数据,出口从队列里面读数据
左侧多线程往入口处添加完数据,任务就结束了;右侧只要依次从水管里取数据就行了。
异步完成的任务
比如京东下单,下单后付完钱,相当于把消息堆在了水管里,后台会有线程去接收这个单的消息,然后去库房,发货,走物流,直到接收货物并签收完,点击完成,整个流程才走完。
客户交完钱后,丢了个消息在这个队列中,会给客户返回一个结果,告知你已经买了这个商品;而后面接收订单消息,发货,物流都是后面的"进程"或"线程"干的事情。
所以,一般在异步处理问题时候,都会用到消息队列处理的这种思想。
使用multiprocessing里面的Queue来实现消息队列。
语法:
1
2
3
4
|
from mutliprocessing import Queue
q = Queue
q.put(data) data = q.get(data)
|
举例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
from multiprocessing import Queue, Process
def write(q):
for i in [ 'a' , 'b' , 'c' , 'd' ]:
q.put(i)
print ( 'put {0} to queue' . format (i))
def read(q):
while 1 :
result = q.get()
print ( "get {0} from queue" . format (result))
def main():
q = Queue()
pw = Process(target = write,args = (q,))
pr = Process(target = read,args = (q,))
pw.start()
pr.start()
pw.join()
pr.terminate() #停止
# 相当于join,等pr完成以后,当whlie没有任何执行后,结束。
if __name__ = = '__main__' :
main()
|
返回结果:
1
2
3
4
5
6
7
8
|
put a to queue get a from queue put b to queue get b from queue put c to queue get c from queue put d to queue get d from queue |
PIPE:
多进程里面有个pipe的方法来实现消息队列:
1. Pipe 方法返回(conn1, conn2)代表一个管道的两端。PIPE方法有个deplex参数,如果deplex参数为True(默认值),那么这个管道是全双工模式,也就是说conn1和conn2均可收发。duplex为False,conn1只负责接收消息,conn2负责发送消息。
2.send 和recv方法分别是发送和接受消息的方法。close方法表示关闭管道,当消息接收结束以后,关闭管道。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
import time
from multiprocessing import Pipe, Process
def proc1(pipe):
for i in xrange ( 1 , 10 ):
pipe.send(i)
print ( "send {0} to pipe" . format (i))
time.sleep( 1 )
def proc2(pipe):
n = 9
while n > 0 :
result = pipe.recv()
print ( "recv {0} from pipe" . format (result))
n - = 1
def main():
pipe = Pipe(duplex = False )
print ( type (pipe))
p1 = Process(target = proc1, args = (pipe[ 1 ],))
p2 = Process(target = proc2, args = (pipe[ 0 ],)) #接收写0
p1.start()
p2.start()
p1.join()
p2.join()
pipe[ 0 ].close()
pipe[ 1 ].close()
if __name__ = = '__main__' :
main()
|
返回结果(逐行打印):
本文转自 听丶飞鸟说 51CTO博客,原文链接:http://blog.51cto.com/286577399/2051155