Python进程间通信 multiProcessing Queue队列实现详解

  

Python进程间通信 multiProcessing Queue队列实现详解

什么是进程间通信

在操作系统中,进程是由操作系统抽象出来的程序执行单元,每个进程与其他进程相互独立,都有独立的地址空间、数据、代码以及系统资源。不同进程之间互相隔离,如果需要在不同的进程之间传递数据,就需要通过进程间通信(IPC)来实现。

Python中有多种方法实现进程间通信,其中最常用的是multiProcessing Queue队列。

multiProcessing Queue队列的原理

multiProcessing Queue队列是基于共享内存的机制实现的,可以在不同的进程之间传递数据。Queue的实现中有一个Queue Manager,负责维护Queue中的数据,每个进程都可以将自己的数据写入Queue中,同时也可以从Queue中读取其他进程写入的数据。

在使用Queue时,每个进程都必须连接到共享的Queue Manager并且执行相应的操作,这样才能够进行数据的传输。为了方便使用,Python中提供了multiprocessing模块,其中Queue的实现就在这个模块中。

使用multiProcessing Queue队列的基本步骤

  1. 创建一个Queue Manager对象,用于维护队列中的数据;
  2. 创建多个进程,每个进程通过连接到Queue Manager,向队列中写入自己的数据或从队列中读取其他进程写入的数据;
  3. 等待所有进程执行完毕,并关闭Queue Manager管理的进程之间数据的交互。

示例一:使用Queue实现进程间的通信

from multiprocessing import Manager, Process

def send_data(queue, data):
    """
    向队列中写入数据
    """
    queue.put(data)

def recv_data(queue):
    """
    从队列中读取数据
    """
    data = queue.get()
    return data

if __name__ == '__main__':
    manager = Manager()
    queue = manager.Queue()

    # 创建进程,向队列中写入数据
    p_send = Process(target=send_data, args=(queue, 'hello, world!'))
    p_send.start()

    # 创建进程,从队列中读取数据
    p_recv = Process(target=recv_data, args=(queue,))
    p_recv.start()

    # 等待所有进程执行完毕
    p_send.join()
    p_recv.join()

示例二:使用Queue实现多进程之间的通讯

from multiprocessing import Manager, Process
import time

def send_data(queue, pid):
    """
    向队列中写入数据
    """
    while True:
        message = 'Hello from process %d' % pid
        queue.put(message)
        time.sleep(1)

def recv_data(queue):
    """
    从队列中读取数据
    """
    while True:
        message = queue.get()
        print('Message received: ' + message)

if __name__ == '__main__':
    manager = Manager()
    queue = manager.Queue()

    # 创建3个进程,每个进程向队列中写入数据
    for i in range(3):
        Process(target=send_data, args=(queue,i)).start()

    # 创建一个进程,从队列中读取数据
    Process(target=recv_data, args=(queue,)).start()

    while True:
        time.sleep(1)

以上两个示例说明如何使用multiProcessing Queue队列实现进程间通信,第一个示例演示的是两个进程之间的通信,第二个示例演示的是多个进程之间的通信。

相关文章