我试图了解多进程池是如何工作的。在下面的编程中,我创建了一个包含 4 个进程的池。
我使用回调函数调用 apply_async
,该函数应该更新名为 result_list
的列表
import Queue
from multiprocessing import Process
from multiprocessing import Pool
result_list = []
def foo_pool(q): #Function for each process
print "foo_pool"
if(q.qsize() > 0):
number = q.get()
return number * 2
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
if __name__ == "__main__":
q = Queue.Queue()
for i in range(4):
q.put(i + 1) #Put 1..4 in the queue
p = Pool(4)
p.apply_async(foo_pool, args = (q, ), callback = log_result)
我意识到我不需要在这里使用队列。但我正在为另一个需要我使用队列的程序测试这个。
当我运行程序时,函数 foo_pool 没有被调用。打印语句 print "foo_pool"
不执行。这是为什么?
最佳答案
粗略地说,apply_async只调度异步任务,但不运行它。需要调用p.close()
和p.join()
来触发执行或者r = p.apply_async()
和r.get()
.
关于python - 对进程池使用带有回调函数的 apply_async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36904237/