2017-09-04 7 views
2

プロセスの中でmultiprocessing.pool.mapと呼んでいます。プロセス内で呼び出されているブロッキングマルチプロセッシングpool.map

run()関数内で初期化すると機能します。インスタンシエーション時に初期化されても、インスタンス化されません。

私はこの現象の理由を理解できませんか?このプロセスではどうなりますか?それはその機能のためのパイプやスレッドに依存しているので、私のpython 3.6

from multiprocessing import Pool, Process, Queue 

def DummyPrinter(key): 
    print(key) 

class Consumer(Process): 
    def __init__(self, task_queue): 
     Process.__init__(self) 
     self.task_queue = task_queue 
     self.p = Pool(1) 

def run(self): 
    p = Pool(8) 
    while True: 
     next_task = self.task_queue.get() 
     if next_task is None: 
      break 

     p.map(DummyPrinter, next_task) # Works 
     #self.p.map(DummyPrinter, next_task) # Does not Work 
    return 

if __name__ == '__main__': 
    task_queue = Queue() 
    Consumer(task_queue).start() 

    task_queue.put(range(5)) 
    task_queue.put(None) 
+0

あなたはウィンドウを使用しているとしますか? –

+0

Ubuntuで、 – bold

+0

を編集すると、動作していないコードを表示できますか?私はそのような問題を解決したと思う。私はそれを見つけることができます –

答えて

2

multiprocessing.Pool日午前 は、複数のプロセスで共有することはできません。

__init__のメソッドは親プロセスで実行され、runロジックは子プロセスに属します。

Processオブジェクトをサブクラス化することは、通常は直感的ではないので、通常はお勧めします。

以下のようなロジックは、責任の実際の分担をよりよく示すでしょう。

def function(task_queue): 
    """This runs in the child process.""" 
    p = Pool(8) 
    while True: 
     next_task = self.task_queue.get() 
     if next_task is None: 
      break 

     p.map(DummyPrinter, next_task) # Works 

def main(): 
    """This runs in the parent process.""" 
    task_queue = Queue() 
    process = Process(target=function, args=[task_queue]) 
    process.start() 
関連する問題