为什么ProcessPoolExecutor可以连续工作?

时间:2020-04-25 20:27:54

标签: python parallel-processing concurrent.futures

from concurrent.futures import ProcessPoolExecutor
import os
import time

def parInnerLoop(item):
    print(f'Processing {os.getpid()} started on {item}')
    time.sleep(3)
    print(f'Processing {os.getpid()} done on {item}')

def main():
    executor = ProcessPoolExecutor(max_workers=4)

    for itemNo in range(10):
        executor.submit(parInnerLoop(itemNo))

if __name__ == '__main__':
    main()

我要实现的是并行for循环,类似于MatLab,例如:

parfor itemNo = 0:9
    parInnerLoop(itemNo);
end

我得到的是:所有os.getpid都相同,并且执行顺序发生。有帮助吗?

Windows,VSCodium / VSCode,Python 3.7.3

1 个答案:

答案 0 :(得分:1)

如@Klaus所述,需要从executor.submit(parInnerLoop(itemNo))更改为executor.submit(parInnerLoop, itemNo)