2017-09-04 106 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

我想你正在使用Windows呢? –

+0

在Ubuntu上,編輯 – bold

+0

可以顯示代碼_doesn't_工作,而不是工作?我想我解決了這樣的問題。讓我找到 –

回答

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() 
相關問題