• 技术文章 >Python技术 >Python高级

    Python如何进行进程间的通信

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-06-29 11:59:08原创1781

    进程间的通信-Queue

    1. Queue的使用

    可以使用multiprocessing模块的Queue实现多进程之间的数据传递,Queue本身是一个消息列队程序,首先用一个小实例来演示一下Queue的工作原理:

    #-*- coding:utf-8 -*-
    from multiprocessing import Queue
    #创建一个Queue对象,最多可接受三条put消息
    q = Queue(3) 
    q.put("消息1")
    q.put("消息2")
    print(q.full())
    q.put("消息3")
    print(q.full())
    try:
        q.put("消息4",True,2)
    except :
        print("消息队列已满,现有消息数量:%s"%q.qsize())
    try:
        q.put_nowait("消息5")
    except :
        print("消息队列已满,现有消息数量:%s"%q.qsize())
    #推荐方式,先判断消息队列是否已满,在写入
    if not q.full():
        q.put_nowait("消息6")
    #读取消息时,先判断消息队列是否为空,在读取
    if not q.empty():
        for i in range(q.qsize()):
            print(q.get_nowait())

    运行结果为:

    False
    True
    消息队列已满,现有消息数量:3
    消息队列已满,现有消息数量:3
    消息1
    消息2
    消息3

    说明

    初始化Queue()对象时(例如:q=Queue()),若括号中没有指定可接收的消息数量,或数量为负值,那么就代表可接受的消息数量没有上限(直到内存的尽头);

    Queue.qsize():返回当前队列包含的消息数量;

    Queue.empty():如果队列为空,返回True,反之False ;

    Queue.full():如果队列满了,返回True,反之False;

    Queue.get([block[, timeout]]):获取队列中的一条消息,然后将其从列队中移除,block默认值为True;

    1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果为空,此时程序将被阻塞(停在读取状态),直到从消息列队读到消息为止,如果设置了timeout,则会等待timeout秒,若还没读取到任何消息,则抛出"Queue.Empty"异常;

    2)如果block值为False,消息列队如果为空,则会立刻抛出"Queue.Empty"异常;

    Queue.get_nowait():相当Queue.get(False);

    Queue.put(item,[block[, timeout]]):将item消息写入队列,block默认值为True;

    1)如果block使用默认值,且没有设置timeout(单位秒),消息列队如果已经没有空间可写入,此时程序将被阻塞(停在写入状态),直到从消息列队腾出空间为止,如果设置了timeout,则会等待timeout秒,若还没空间,则抛出"Queue.Full"异常;

    2)如果block值为False,消息列队如果没有空间可写入,则会立刻抛出"Queue.Full"异常;

    Queue.put_nowait(item):相当Queue.put(item, False);

    2. Queue实例

    我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:

    from multiprocessing import Process
    from multiprocessing import Queue
    import os
    import time
    import random
    #写数据进程执行的代码
    def write(q):
        for value in ["A","B","C"]:
            print("Put %s to Queue "%value)
            q.put(value)
            time.sleep(random.random())
       
    #读取数据进程的代码   
    def read(q):
        while True:
            if not q.empty():
                value = q.get(True)
                print("Get %s from Queue "%value)
                time.sleep(random.random())
            else:
                break
    if __name__ == '__main__':
        #父进程创建Queue,并传递给各个子进程
        q = Queue()
        pw = Process(target = write,args=(q,))
        pr = Process(target = read,args=(q,))
        #启动子进程pw,写入
        pw.start()
        #等待pw结束
        pw.join()
        #启动子进程pr,读取
        pr.start()
        pr.join()
        print("所有数据都写入并且读完")

    运行结果为:

    Put A to Queue 
    Put B to Queue 
    Put C to Queue 
    Get A from Queue 
    Get B from Queue 
    Get C from Queue

    所有数据都写入并且读完。

    3. 进程池中的Queue

    如果要使用Pool创建进程,就需要使用multiprocessing.Manager()中的Queue(),而不是multiprocessing.Queue(),否则会得到一条如下的错误信息:

    RuntimeError: Queue objects should only be shared between processes through inheritance.

    #coding=utf-8
    from multiprocessing import Manager
    from multiprocessing import Pool
    import os
    import time
    import random
    def reader(q):
        print("reader启动(%d),父进程为(%d)"%(os.getpid(),os.getppid()))
        for i in range(q.qsize()):
            print("reader从Queue获取到的消息时:%s"%q.get(True))
    def writer(q):
        print("writer启动(%d),父进程为(%d)"%(os.getpid(),os.getppid()))
        for i in "Se7eN_HOU":
            q.put(i)
    if __name__ == '__main__':
        print("-------(%d) Start-------"%os.getpid())
        #使用Manager中的Queue来初始化
        q = Manager().Queue()
        po = Pool()
        #使用阻塞模式创建进程,这样就不需要在reader中使用死循环了,可以让writer完全执行完成后,再用reader去读取
        po.apply(writer,(q,))
        po.apply(reader,(q,))
        po.close()
        po.join()
        print("-------(%d) End-------"%os.getpid())

    运行结果为:

    -------(880) Start-------
    writer启动(7744),父进程为(880)
    reader启动(7936),父进程为(880)
    reader从Queue获取到的消息时:S
    reader从Queue获取到的消息时:e
    reader从Queue获取到的消息时:7
    reader从Queue获取到的消息时:e
    reader从Queue获取到的消息时:N
    reader从Queue获取到的消息时:_
    reader从Queue获取到的消息时:H
    reader从Queue获取到的消息时:O
    reader从Queue获取到的消息时:U
    -------(880) End-------

    相关推荐:

    Python中的进程池是什么

    专题推荐:python 进程 通信
    品易云
    上一篇:Python中的进程池是什么 下一篇:Python中的子进程是什么

    相关文章推荐

    • Python中的多进程是什么• Python中的进程是什么• Python中的进程池是什么

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网