在python中为迭代任务创建n个进程

在python中为迭代任务创建n个进程,python,process,locking,multiprocessing,Python,Process,Locking,Multiprocessing,我对python多处理模块有一个复杂的问题。 我构建了一个脚本,在一个地方必须为specyfic列表中的每个元素调用一个多参数函数(call_函数)。我的想法是定义一个整数‘N’,并将这个问题划分为单个子进程 li=[a,b,c,d,e] #elements are int's for element in li: call_function(element,string1,string2,int1) call_summary_function() Summary函数将分析循环的所有

我对python多处理模块有一个复杂的问题。 我构建了一个脚本,在一个地方必须为specyfic列表中的每个元素调用一个多参数函数(call_函数)。我的想法是定义一个整数‘N’,并将这个问题划分为单个子进程

li=[a,b,c,d,e] #elements are int's
for element in li:
    call_function(element,string1,string2,int1)

call_summary_function()
Summary函数将分析循环的所有迭代所获得的结果。现在,我希望每个迭代都由单个子流程执行,但总共不能超过N个子流程。如果是这样,主进程应该等到其中一个子进程结束,然后执行另一个迭代。此外,需要在所有子进程完成后调用call_sumary_函数

我已经尽了最大努力使用多处理模块、锁和全局变量来保持子进程的实际运行数量(与N相比),但每次都会出现错误

//--------------编辑-------------//

首先,主要工艺代码:

MAX_PROCESSES=3
lock=multiprocessing.Lock()
processes=0
k=0
while k < len(k_list):

    if processes<=MAX_PROCESSES: # running processes <= 'N' set by me

        p = multiprocessing.Process(target=single_analysis, args=(k_list[k],main_folder,training_testing,subsets,positive_name,ratio_list,lock,processes))
        p.start()
        k+=1

    else: time.sleep(1)


while processes>0: time.sleep(1)
我得到的错误是int值(processs变量)总是等于0,因为
single_analysis()
函数似乎创建了新的局部变量
processs

当我将流程更改为全局并将其导入到函数中的
len(li)
中时,我得到
len(li)
乘以1

您所描述的内容非常适合-特别是其方法:


p.map
将为
li
列表中的每个
元素调用
call_函数(string1、string2、int1、element)
<代码>结果
将是一个列表,其中包含对
调用函数
的每次调用返回的值。您可以将该列表传递给
call\u summary\u function
以处理结果。

您可以显示您尝试过的代码(使用
多处理
)吗(这会导致错误)?多处理.Pool类可以执行您想要的操作。它为你做了让N个孩子活着的工作。你试过了吗?汤姆·道尔顿:试过了,我添加了specyfic description:)t德莱尼:我有一个红色警告:使用池不能调用具有多个参数的函数。@maciek你可以使用
Pool
调用具有多个参数的函数。看到我的答案了。非常感谢!我以前试过Pool(),但我错过了您当天保存的“部分”:
def single_analysis(k,main_folder,training_testing,subsets,positive_name,ratio_list,lock,processes):

lock.acquire()
processes+=1
lock.release()

#stuff to do

lock.acquire()
processes-=1
lock.release()
import multiprocessing
from functools import partial

def call_function(string1, string2, int1, element):
    # Do stuff here

if __name__ == "__main__":
    li=[a,b,c,d,e]
    p = multiprocessing.Pool(N)  # The pool will contain N worker processes.

    # Use partial so that we can pass a method that takes more than one argument to map.
    func = partial(call_function, string1,string2,int1)

    results = p.map(func, li)
    call_summary_function(results)