【发布时间】:2019-04-15 20:04:29
【问题描述】:
注意:我不需要进程/线程之间的任何通信,我只对完成信号感兴趣(这就是我将这个问题作为一个新问题发布的原因,因为所有其他示例我'已经发现彼此之间进行了通信)。
如何在 Python 3 中使用 multiprocessing 包来并行化以下代码(最终目标是让它运行得更快):
a = 123
b = 456
for id in ids: # len(ids) = 10'000
# executes a binary with CLI flags
run_binary_with_id(id, a, b)
# i.e. runs "./hello_world_exec --id id --a a --b b" which takes about 30 seconds on average
我尝试了以下方法:
import multiprocessing as mp
def run_binary_with_id(id, a, b):
run_command('./hello_world_exec --id {} --a {} --b {}'.format(id, a, b))
if __name__ == '__main__':
ctx = mp.get_context('spawn')
q = ctx.Queue()
a = 123
b = 456
ids = range(10000)
for id in ids:
p = ctx.Process(target=run_binary_with_id, args=(id,a,b))
p.start()
p.join()
# The binary was executed len(ids) number of times, do other stuff assuming everything's completed at this point
或
for id in ids:
map.apply_async(run_binary_with_id, (id,a,b))
在similar question 中,答案如下:
def consume(iterator):
deque(iterator, max_len=0)
x=pool.imap_unordered(f,((i,j) for i in range(10000) for j in range(10000)))
consume(x)
我完全不明白(为什么我需要这个consume())。
【问题讨论】:
标签: python-3.x python-multiprocessing python-multithreading