以下是一个示例代码,展示了如何并行从一个进程中读取n个管道的数据:
import os
from multiprocessing import Process, Pipe
def read_pipe(conn):
while True:
data = conn.recv()
if data == 'END':
break
print('Received:', data)
if __name__ == '__main__':
# 创建n个管道
n = 3
pipes = []
processes = []
for _ in range(n):
parent_conn, child_conn = Pipe()
pipes.append(parent_conn)
p = Process(target=read_pipe, args=(child_conn,))
processes.append(p)
# 启动子进程
for p in processes:
p.start()
# 从每个管道中发送数据
for i, conn in enumerate(pipes):
for j in range(5):
conn.send(f'Message {j} from pipe {i}')
# 给每个子进程发送结束信号
for conn in pipes:
conn.send('END')
# 等待子进程结束
for p in processes:
p.join()
print('All processes finished.')
上述代码中,首先创建了n个管道,并使用Pipe()
函数返回的两个连接对象parent_conn
和child_conn
来建立管道的两个端点。然后,使用Process
类创建了n个子进程,并将每个子进程的连接对象child_conn
作为参数传递给read_pipe
函数。
在read_pipe
函数中,使用recv()
方法从连接对象中读取数据,并在接收到结束信号'END'
之前不断循环读取数据。
在主进程中,首先启动所有的子进程,然后使用每个管道的连接对象parent_conn
发送数据。在发送完数据后,给每个子进程发送结束信号'END'
。
最后,使用join()
方法等待所有子进程结束,并打印出提示信息。
上一篇:并行从异步方法中遍历数组
下一篇:并行CRC多项式