欢迎访问宙启技术站
智能推送

使用Python的multiprocessing.connection在进程间进行通信

发布时间:2023-12-27 06:52:19

在Python中,可以使用multiprocessing.connection模块进行进程间通信。这个模块提供了两种通信方式:管道(pipe)和套接字(socket)。

下面是一个使用管道进行通信的例子:

首先,创建一个监听进程来接收和处理传入的连接。下面是一个简单的示例:

from multiprocessing import Process, Pipe

# 这个函数在子进程中运行,用来接收消息并做出响应
def handle_connection(conn):
    while True:
        msg = conn.recv()  # 接收消息
        if msg == 'exit':
            break
        print('Received message:', msg)
        conn.send('ACK')  # 发送响应

# 创建管道
parent_conn, child_conn = Pipe()

# 创建子进程,并将管道的一端传递给子进程
p = Process(target=handle_connection, args=(child_conn,))
p.start()

# 在父进程中发送消息并接收响应
parent_conn.send('Hello from parent')
print('Received response:', parent_conn.recv())

# 关闭连接和进程
parent_conn.send('exit')
p.join()

在这个例子中,我们在父进程中创建了一个管道,然后将管道的一端传递给子进程。子进程会在另一个进程中运行,并等待接收父进程发送的消息。当子进程收到消息后,会打印消息内容并发送一个响应。父进程可以使用管道的另一端来发送消息给子进程,并接收子进程的响应。

下面是一个使用套接字进行通信的例子:

from multiprocessing import Process
from multiprocessing.connection import Listener, Client

# 这个函数在子进程中运行,用来接收消息并做出响应
def handle_connection(conn):
    while True:
        msg = conn.recv()  # 接收消息
        if msg == 'exit':
            break
        print('Received message:', msg)
        conn.send('ACK')  # 发送响应

# 创建监听进程来接收连接
address = ('localhost', 6000)
listener = Listener(address)

# 创建子进程,并使用套接字连接到监听进程
p = Process(target=handle_connection, args=(Client(address),))
p.start()

# 在父进程中发送消息并接收响应
conn = listener.accept()  # 接受连接
conn.send('Hello from parent')
print('Received response:', conn.recv())

# 关闭连接和进程
conn.send('exit')
p.join()
listener.close()

在这个例子中,我们先创建一个监听进程,用来接收连接。然后,我们在父进程中连接到监听进程,并与之建立连接。之后,我们创建一个子进程,将与监听进程的连接传递给子进程。子进程在另一个进程中运行,并等待接收父进程发送的消息。当子进程收到消息后,会打印消息内容并发送一个响应。父进程可以使用连接来发送消息给子进程,并接收子进程的响应。

总结起来,使用multiprocessing.connection模块可以很方便地在Python中进行进程间通信。我们可以使用管道或套接字来建立连接,并通过连接发送和接收消息。这些例子只是演示了一些基本用法,你可以根据自己的需求进行修改和扩展。