python使用ProcessPoolExecutor easiliy?

时间:2016-01-27 05:07:25

标签: python multiprocessing

首先我像这样使用ProcessPoolExecutor

def s(i):
    time.sleep(1)
    return i

futs = []
with ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(WORKER_CNT):
        print executor.submit(s, i,).result()

然后我发现这不是平行的,然后我改为:

def s(i):
    time.sleep(1)
    return i

futs = []
with ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(WORKER_CNT):
        futs.append(executor.submit(s, i,))

for f in futs:
    print f.result()

然后我开始担心WORKER_CNT可能太大了,我需要等待很长时间才能看到最后的结果,所以我改为:

def s(i):
    time.sleep(1)
    return i

futs = []
with ProcessPoolExecutor(max_workers=10) as executor:
    for i in range(WORKER_CNT):
        futs.append(executor.submit(s, i,))
        if len(futs) == 10:
            for f in futs:
                print f.result()
            futs = []

这一次,我每次都可以处理10我想知道我可以更轻松地处理这个问题吗?

1 个答案:

答案 0 :(得分:0)

您想使用Executor类的map 方法

def s(i):
    time.sleep(1)
    return i

with ProcessPoolExecutor(max_workers=10) as executor:
    results = executor.map(s, range(WORKER_CNT))

它有一些其他选项来控制执行的执行方式。

请注意,results 不是列表。它是一个迭代器,它在计算时接收值。所以下面的代码:

with ProcessPoolExecutor(max_workers=10) as executor:
    for result in executor.map(s, range(WORKER_CNT)):
        print(result)

一次只会在内存中保留一个结果,因为它们会在几分之一秒内耗尽,并且需要更长的时间来制作。