2017-01-16 11 views
3

私は答えがノーだと思います。 (なぜhereのコメントの理由についての仮説を見てください)しかし、パイプ/キュー/マネージャを使用してプロセスを分岐させた後に、プロセス間で新しい共有(生の)配列を構築できるのは本当にうれしいでしょう。セットアップ。私はOSに精通していません。これまで起きていることの見込みはありますか?Pythonマルチプロセッシングでフォーク後に共有メモリを作成することはできますか?

本当の共有配列と同じ読み書き速度を提供する賢明な回避策(おそらくmemmap?)はありますか?

+0

これはすでに回答済みです(http://stackoverflow.com/q/7419159/6442723)年前...より良い検索が必要です! –

答えて

2

私はそれが既存のファイルのメモリマップを共有することによって行うことができると思います。以下の例を複数回実行し、出力を監視してください。すべてのプロセスが共有ファイルを開いたら、ディスク上のファイルを削除して共有メモリを使用し続けることができます。ここではファイルロックが使用されていますが、これは最善の方法ではないかもしれません。

#!/usr/bin/env python3 

import fcntl 
import mmap 
import os 
import time 
from contextlib import contextmanager, suppress 

# Open (and create if necessary) a file of shared_size. 
# Every sleep_timeout seconds: 
# - acquire an exclusive lock, 
# - read the data, and 
# - write new data 

# 1kiB for example 
shared_size = 1024 
filename = "shared_data.bin" 
sleep_timeout = 1 

# Context manager to grab an exclusive lock on the 
# first length bytes of a file and automatically 
# release the lock. 
@contextmanager 
def lockf(fileno, length=0): 
    try: 
    fcntl.lockf(fileno, fcntl.LOCK_EX, length) 
    yield 
    finally: 
    fcntl.lockf(fileno, fcntl.LOCK_UN, length) 

def ensure_filesize(f, size): 
    # make sure file is big enough for shared_size 
    f.seek(0, os.SEEK_END) 
    if f.tell() < size: 
    f.truncate(size) 

def read_and_update_data(f): 
    f.seek(0) 
    print(f.readline().decode()) 
    f.seek(0) 
    message = "Hello from process {} at {}".format(os.getpid(), time.asctime(time.localtime())) 
    f.write(message.encode()) 

# Ignore Ctrl-C so we can quit cleanly 
with suppress(KeyboardInterrupt): 
    # open file for binary read/write and create if necessary 
    with open(filename, "a+b") as f: 
    ensure_filesize(f, shared_size) 

    # Once all processes have opened the file, it can be removed 
    #os.remove(filename) 

    with mmap.mmap(f.fileno(), shared_size) as mm: 
     while True: 
     with lockf(f.fileno(), length=shared_size): 
      read_and_update_data(mm) 
     time.sleep(sleep_timeout) 
関連する問題