繁体   English   中英

如何使用多处理处理带有 break 语句的 Python for 循环?

[英]How to use multiprocessing for a Python for loop with a break statement?

如何并行化具有 if 条件的 for 循环。 如果满足该条件,则无需继续循环。 如果我可以为此使用多处理,那就太好了。

for i in xrange(N):
    x = do_something_with()
    if x == 0:
        break

上面的代码可以在Python中并行化吗?

您可以在作业处于活动状态时终止multiprocessing.Pool ,它将终止子进程。 如果你可以提前生成你的参数, imap_unordered可以用来拉入结果并在满足条件时终止池。 处理池中其他作业的子进程将被终止,因此它们不会返回其他结果。

import multiprocessing as mp
import time

def worker(x):
    print('work item', x)
    time.sleep(x)
    result = x - 5
    if result == 0:
        print('termination condition')
    print('work item', x, 'done')
    return result

if __name__ == '__main__':
    p = mp.Pool(4)
    for result in p.imap_unordered(worker, range(20), chunksize=1):
        if result == 0:
            print('terminating')
            p.terminate()
            break
    print('done')

结果是

work item 0
work item 1
work item 0 done
work item 4
work item 3
work item 2
work item 1 done
work item 5
work item 2 done
work item 6
work item 3 done
work item 7
work item 4 done
work item 8
termination condition
work item 5 done
work item 9
terminating
done

请注意,有些作业已启动但尚未完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM