Process Pools
1. apply (func[, args[, kwds]])
- 只能执行1次(只能输入一次参数)
- 支持多个参数(参数统一为元祖类型)
- 阻塞(只能等待这行代码执行完,才会执行下面的代码)
- 返回结果为函数执行结果
2. apply_async (func[, args[, kwds[, callback[, error_callback]]]])
- 异步,不阻塞(子进程先跑着,会接着执行主进程代码)
- 返回结果为 AsyncResult, 可查看结果有没有准备好,使用.get()获取结果
3. map (func, iterable[, chunksize])
- 可多次函数(迭代参数)
- 目标函数只支持 单参数 输入
- 阻塞
- 返回结果为list,顺序与输入的参数迭代器的顺序一致
4. map_async (func, iterable[, chunksize[, callback[, error_callback]]])
5. imap(func, iterable[, chunksize])
- 异步,不阻塞
- 输出为迭代器,不是list,顺序和输入参数一致
6. imap_unordered (func, iterable[, chunksize])
7. starmap (func, iterable[, chunksize])
- 支持目标函数为多参数:Demo iterable: [(1,2), (3, 4)]
8. starmap_async (func, iterable[, chunksize[, callback[, error_callback]]])
9. close()
- 关闭池口,不允许再向池内添加任务
- 所有任务完成后,子进程都将自动退出
10. terminate()
11. join()
Example
from multiprocessing import Pool
def add(a, b):
return a + b
if __name__ == '__main__':
with Pool(processes=4) as pool:
results = pool.starmap_async(add, [(1, 2), (3, 4), (5, 6), (7, 8)])
while not results.ready():
# Do other work while waiting for results
pass
output = results.get()
print(output)