假设我有两种方法来完成同一个任务:
from multiprocessing import Pool
pool = Pool(4)
def func(*args):
# do some slow operations
return something
dates = ['2011-01-01', ' 2011-01-02', ... , '2017-01-01']
other_args = [1, 2, 3, 'c', 'test', 'pdf')]
# approach 1:
res = [pool.apply_async(func, [day] + other_args) for day in dates]
list_of_results = [x.get() for x in res]
# approach 2: create an iterable of iterables
args = [[day] + other_args for day in dates]
list_of_results = pool.starmap(func, args)
我知道apply_async会立即返回,但是如果func函数还没有运行完,x.get()可能仍然会阻塞主线程...这两种方法之间一定会有性能差异吗?