python学习—Day45—消息队列

本文介绍消息队列的概念及其实现方式,包括通过multiprocessing模块中的Queue和Pipe进行进程间通信的具体示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

消息队列:

消息队列是在消息传输过程中保存消息的容器。
消息队列最经典的用法就是消费者和生产者之间通过消息管道来传递消息,消费者和生产者是不通的进程。生产者往管道中写消息,消费者从管道中读消息。
操作系统提供了很多机制来实现进程间的通信,multiprocessing模块就提供了Queue和pipe两种方法来实现。

#@File :queue_demo1.py
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执行完成,这里就结束。

if __name__ == "__main__":
    main()
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


通过mutiprocess里面的pipe来实现消息队列:
Pipe方法返回(conn1, conn2)代表一个管道的两个端。Pipe方法有duplex参数,如果duplex参数为True(默认值),那么这个管道是全双工模式,也就是说conn1和conn2均可收发。duplex为False,conn1只负责接受消息,conn2只负责发送消息。
send和recv方法分别是发送和接受消息的方法,close方法表示关闭管道,当接受结束以后,关闭管道。

#@File :pipe_demo1.py
from multiprocessing import Pipe, Process

import time


def proc1(pipe):
    for i in xrange(1, 10):
        pipe.send(i)
        print("send {0} to pipe".format(i))
        time.sleep(1)
        print("#################   one time    ##########")

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],))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    pipe[0].close()
    pipe[1].close()
if __name__ == "__main__":
    main()
<type 'tuple'>
send 1 to pipe
recv 1 from pipe
#################   one time    ##########
send 2 to pipe
recv 2 from pipe
#################   one time    ##########
send 3 to piperecv 3 from pipe


#################   one time    ##########
send 4 to pipe
recv 4 from pipe
#################   one time    ##########
send 5 to pipe
recv 5 from pipe
#################   one time    ##########
send 6 to pipe
recv 6 from pipe
#################   one time    ##########
send 7 to pipe
recv 7 from pipe
#################   one time    ##########
send 8 to pipe
recv 8 from pipe
#################   one time    ##########
send 9 to pipe
recv 9 from pipe
#################   one time    ##########




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值