我想在一个进程中调用一个multiprocessing.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)
请您参考如下方法:
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()
