多处理冻结计算机

时间:2016-10-06 09:37:58

标签: python windows python-multiprocessing

我通过使用多处理改进了我的执行时间,但我不确定PC的行为是否正确,它会冻结系统直到所有进程完成。 我使用的是Windows 7和Python 2.7。

也许我犯了一个错误,这就是我所做的:

def do_big_calculation(sub_list, b, c):
    # do some calculations here with the sub_list

if __name__ == '__main__':
    list = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
    jobs = []
    for sub_l in list :
        j = multiprocessing.Process(target=do_big_calculation, args=(sub_l, b, c))
        jobs.append(j)
    for j in jobs:
        j.start()

1 个答案:

答案 0 :(得分:2)

在这里,您要为每项任务创建1 Process。这将并行运行您的所有任务,但由于您的调度程序需要管理许多进程,因此会给您的计算机带来沉重的开销。这会导致系统冻结,因为您的程序使用了太多的资源。

此处的解决方案可能是使用multiprocessing.Pool同时执行某些任务来运行给定数量的进程:

import multiprocessing as mp

def do_big_calculation(args):
    sub_list, b, c = args
    return 1

if __name__ == '__main__':
    b, c = 1, 1
    ll = [([1, 2, 3, 4], b, c),
          ([5, 6, 7, 8], b, c),
          ([9, 10, 11, 12], b, c)]
    pool = mp.Pool(4)
    result = pool.map(do_big_calculation, ll)
    pool.terminate()
    print(result)

如果您准备使用第三方库,您还可以查看concurrent.futures(您需要在python2.7中安装它,但它存在于python3.4 +中)或joblib (提供点子):

from joblib import Parallel, delayed

def do_big_calculation(sub_list, b, c):
    return 1

if __name__ == '__main__':
    b, c = 1, 1
    ll = [([1, 2, 3, 4], b, c),
          ([5, 6, 7, 8], b, c),
          ([9, 10, 11, 12], b, c)]
    result = Parallel(n_jobs=-1)(
        delayed(do_big_calculation)(l, b, c) for l in ll)
    print(result)

这种库的主要优点是它正在开发,而python2.7中的multiprocessing被冻结了。因此,相对经常有错误修复和改进 它还实现了一些聪明的工具来减少计算开销。例如,它使用大型numpy数组的内存映射(减少启动所有作业的内存占用量)。

相关问题