reader_conn, writer_conn = Pipe() でpipeを接続してるのはわかります。
共有メモリの場合は、グローバルな変数で値をやり取りしたが、Pipeの場合はその名の通り、一方のスレッドからもう一方のスレッドへ値を渡すときに使われるってことかな。。
from threading import Thread, current_thread from multiprocessing import Pipe from multiprocessing.connection import Connection class Writer(Thread): def __init__(self, conn: Connection): super().__init__() self.conn = conn self.name = "Writer" def run(self) -> None: print(f"{current_thread().name}: Sending rubber duck...") self.conn.send("Rubber duck") class Reader(Thread): def __init__(self, conn: Connection): super().__init__() self.conn = conn self.name = "Reader" def run(self) -> None: print(f"{current_thread().name}: Reading...") msg = self.conn.recv() print(f"{current_thread().name}: Received: {msg}") def main() -> None: reader_conn, writer_conn = Pipe() reader = Reader(reader_conn) writer = Writer(writer_conn) threads = [ writer, reader ] for thread in threads: thread.start() for thread in threads: thread.join() if __name__ == "__main__": main()
$ python3 pipe.py
Writer: Sending rubber duck…
Reader: Reading…
Reader: Received: Rubber duck