最后活跃于 9 months ago

multiprocessing.Pipe 允許 Python 進程之間傳遞資料,適用於需要高效能、雙向通訊的場景,如併發運算或分佈式處理。

timmy 修订了这个 Gist 9 months ago. 转到此修订

1 file changed, 18 insertions

multiprocessing_pipe_example.py(文件已创建)

@@ -0,0 +1,18 @@
1 + from multiprocessing import Process, Pipe
2 +
3 + def worker(conn):
4 + conn.send("Hello from child process") # 傳送訊息
5 + msg = conn.recv() # 接收訊息
6 + print(f"Child received: {msg}")
7 + conn.close()
8 +
9 + if __name__ == "__main__":
10 + parent_conn, child_conn = Pipe() # 建立 Pipe 雙向通道
11 +
12 + p = Process(target=worker, args=(child_conn,))
13 + p.start()
14 +
15 + print(f"Parent received: {parent_conn.recv()}") # 從子進程接收訊息
16 + parent_conn.send("Hello from parent process") # 發送訊息到子進程
17 +
18 + p.join() # 等待子進程結束
上一页 下一页