多处理函数调用

时间:2016-10-04 19:46:41

标签: python multiprocessing

我正在尝试在Python中进行一些多处理。我有一个函数做一些工作并返回一个列表。我想在几个案例中重复这一点。最后,我想得到每个并行调用的返回列表并统一它们(只有一个列表,删除了所有重复项)。

def get_version_list(env):
    list = []
    #do some intensive work
    return list

from multiprocessing import Pool

pool = Pool()

result1 = pool.apply_async(get_version_list, ['prod'])
result2 = pool.apply_async(get_version_list, ['uat'])
#etc, I have six environment to check.

alist = result1.get()
blist = result2.get()

这不起作用(不确定函数调用语法,但我也尝试了其他的东西,没有成功),它给了我一个错误(并且重复了很多,因为我的密集工作正在做大约300个req​​uest.post调用)。

RuntimeError:     尝试在当前进程之前启动新进程     已经完成了自举阶段。

This probably means that you are on Windows and you have
forgotten to use the proper idiom in the main module:

    if __name__ == '__main__':
        freeze_support()
        ...

The "freeze_support()" line can be omitted if the program
is not going to be frozen to produce a Windows executable.

1 个答案:

答案 0 :(得分:1)

您必须将多处理部分放在主函数中,例如:

def get_version_list(env):
    list = []
    print "ENV: " + env
    return list


if __name__ == '__main__':
    from multiprocessing import Pool

    pool = Pool()

    result1 = pool.apply_async(get_version_list, ['prod'])
    result2 = pool.apply_async(get_version_list, ['uat'])
    #etc, I have six environment to check.

    alist = result1.get()
    blist = result2.get()