多进程(3)
1 # 消息队列是在消息的传输过程中保存消息的容器。 2 # 消息队列最经典的用法就是消费者和生成者之间通过消息管道来传递消息,消费者和生成者是不通的进程。 3 # 生产者往管道中写消息,消费者从管道中读消息。 4 # 操作系统提供了很多机制来实现进程间的通信 ,multiprocessing模块就提供了Queue和Pipe两种方法来实现。 5 # 使用multiprocessing里面的Queue来实现消息队列 6 from multiprocessing import Queue, Process 7 8 #写进程 9 def write(q): 10 for i in ["a","b","c","d"]: 11 q.put(i) 12 print("put {0} to queue".format(i)) 13 #读进程 14 def read(q): 15 while 1: 16 result = q.get() 17 print("get {0} from queue".format(result)) 18 #主函数 19 def main(): 20 # 父进程创建Queue,并传给各个子进程: 21 q = Queue() 22 pw = Process(target=write,args=(q,)) 23 pr = Process(target=read,args=(q,)) 24 # 启动子进程pw,写入: 25 pw.start() 26 # 启动子进程pe,读入: 27 pr.start() 28 # 等待pw结束: 29 pw.join() 30 # pr进程里是死循环,无法等待其结束,只能强行终止: 31 pr.terminate() 32 33 if __name__ == "__main__": 34 main() 35 # 36 # 通过Mutiprocess里面的Pipe来实现消息队列: 37 # 1, Pipe方法返回(conn1, conn2)代表一个管道的两个端。 38 # 39 # Pipe方法有duplex参数,如果duplex参数为True(默认值),那么这个管道是全双工模式,也就是说conn1和conn2均可收发。 40 # duplex为False,conn1只负责接受消息,conn2只负责发送消息。 41 # 2, send和recv方法分别是发送和接受消息的方法。close方法表示关闭管道,当消息接受结束以后,关闭管道。 42 import multiprocessing 43 import time 44 def proc1(pipe): 45 for i in xrange(5): 46 print "send: %s" % (i) 47 pipe.send(i) 48 # print(dir(pipe)) 49 time.sleep(1) 50 def proc2(pipe): 51 n = 5 52 while n: 53 print "proc2 rev:", pipe.recv() 54 time.sleep(1) 55 n -= 1 56 if __name__ == "__main__": 57 pipe = multiprocessing.Pipe(duplex=False) 58 print(type(pipe)) 59 print(pipe) 60 p1 = multiprocessing.Process(target=proc1, args=(pipe[1],)) 61 p2 = multiprocessing.Process(target=proc2, args=(pipe[0],)) 62 p1.start() 63 p2.start() 64 p1.join() 65 p2.join() 66 pipe[0].close() 67 pipe[1].close()