#!python # -*- mode: python; Encoding: utf-8; coding: utf-8 -*- # Last updated: <2026/03/22 15:56:46 +0900> """ 共有メモリを使って子スクリプトに画像データを渡して処理させる親スクリプト Windows11 x64 25H2 + Python 3.10.10 64bit """ import subprocess import struct import threading from multiprocessing import shared_memory from PIL import Image def log_reader(pipe): """子の進捗ログを読み取る""" with pipe: for line in iter(pipe.readline, b""): print(f"[Child Log]: {line.decode().strip()}") def run_simple_shm(image_path): # 画像準備 img = Image.open(image_path).convert("RGBA") width, height = img.size img_bytes = img.tobytes() size = len(img_bytes) # 1. 共有メモリの作成とデータ書き込み shm = shared_memory.SharedMemory(create=True, size=size) try: shm.buf[:size] = img_bytes # 2. 子プロセス起動 # セマフォを使わないため、単純な Popen でOK process = subprocess.Popen( ["python", "child_shm.py"], stdin=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0, ) # 進捗表示用スレッド t = threading.Thread(target=log_reader, args=(process.stderr,)) t.start() # 3. メモリ情報を子に送信 # 固定長 64byte の名前と、幅・高さの int を送る header = struct.pack("64sii", shm.name.encode(), width, height) process.stdin.write(header) process.stdin.close() # 4. 子の終了を待つ # これにより、子がメモリを書き換え終わるまで親は待機します(=同期) print("Child process is working...") process.wait() t.join() # 5. 処理結果をメモリから直接読み出して表示 print("Displaying result from Shared Memory.") res_img = Image.frombytes("RGBA", (width, height), shm.buf[:size]) res_img.show() finally: # 6. リソース解放 shm.close() shm.unlink() if __name__ == "__main__": run_simple_shm("input.png")