timmy revised this gist 9 months ago. Go to revision
1 file changed, 18 insertions
multiprocessing_pipe_example.py(file created)
| @@ -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() # 等待子進程結束 | |
Newer
Older