2

マルチプロセッシングを使用してプロジェクトの速度を上げたいです。

from multiprocessing import Queue, Process

def build(something):
    # ... Build something ...
    return something

# Things I want to build.
# Each of these things requires DIFFERENT TIME to be built.
some_things = [a_house, a_rocket, a_car]

#________________________________
# My approach

def do_work(queue, func, args):
    queue.put(func(*args))

# Initialize a result queue
queue = Queue()

# Here I'll need to distribute the tasks (in case there are many)
# through each process. For example process 1 build a house and a rocket 
# and so on. Anyway this is not the case..
procs = [Process(target=do_work, args=thing) for thing in some_things]

# Finally, Retrieve things from the queue
results = []
while not queue.empty():
    results.append(queue.get())

ここでの問題は、プロセスがそのようなものを構築するために終了した場合、他のプロセスが終了するまで待機し、そのようなプロセスに何か他のことをさせたいということです。

どうすればこれを達成できますか?ワーカーのプールを使用できると思いますが、結果を取得する必要があるため、使用方法がよくわかりません。誰かがこれを手伝ってくれる?

4

1 に答える 1

0

使用できるテクニックがいくつかあります。

  1. 共有メモリ配列を使用して、メイン プロセスとすべての子プロセスの間で通信します。辞書を入力値として置き、出力値が計算されたらフラグを設定します。

  2. Pipes を使用して、ジョブの初期データをマスターからワーカーに伝達し、結果をワーカーからマスターに戻します。これは、データを簡単にシリアル化できる場合にうまく機能します。

これらのクラスはどちらもここで詳しく説明されています: http://docs.python.org/2/library/multiprocessing.html

于 2012-12-05T18:19:22.343 に答える