关于Python'的“进程”参数的澄清;s`multiprocessing.Pool`
我的问题是,如果我对范围(8)中的I执行关于Python'的“进程”参数的澄清;s`multiprocessing.Pool`,python,multiprocessing,Python,Multiprocessing,我的问题是,如果我对范围(8)中的I执行[pool.apply_async(myfunc,args=(y,)),如下图所示,并且我使用多个进程初始化池,例如,这里4, 这是否意味着每个函数调用在4个进程上并行运行,而我也并行运行8个函数调用,所以4x8=32个进程,或者它运行4次1个函数调用,直到它们完成,然后再运行另外4个函数调用 import multiprocessing pool = multiprocessing.Pool(processes=4) results = [pool.ap
[pool.apply_async(myfunc,args=(y,))
,如下图所示,并且我使用多个进程初始化池,例如,这里4
,
这是否意味着每个函数调用在4个进程上并行运行,而我也并行运行8个函数调用,所以4x8=32个进程,或者它运行4次1个函数调用,直到它们完成,然后再运行另外4个函数调用
import multiprocessing
pool = multiprocessing.Pool(processes=4)
results = [pool.apply_async(myfunc, args=(i,)) for i in range(8)]
results = [res.get() for res in results]
多处理.Pool
并行运行的进程数永远不会超过您在创建时指定的数目。相反,它会立即生成指定数量的进程,并让它们一直运行,直到关闭/加入池为止。因此,在您的情况下,池
将始终恰好运行四个进程,即使它们都没有做任何工作。如果给池分配八个工作项,前四个工作项将立即并行执行,而后四个工作项将排队。一旦其中一个工作进程完成运行myfunc
,第一个排队项目将开始由现在空闲的工作进程处理
如果运行此示例,您可以亲自看到这一点:
def myfunc(num):
print("in here %s" % num)
time.sleep(2)
print("done with %s" % num)
return num+2
if __name__ == "__main__":
pool = multiprocessing.Pool(4)
results = [pool.apply_async(myfunc, args=(i,)) for i in range(8)]
results = [res.get() for res in results]
print results
输出:
in here 0
in here 1
in here 2
in here 3
<2 second pause>
done with 0
done with 3
done with 1
in here 4
in here 5
in here 6
done with 2
in here 7
<2 second pause>
done with 6
done with 7
done with 4
done with 5
[2, 3, 4, 5, 6, 7, 8, 9]
在这里0
在这里1
在这里2
在这里3
用0完成
完成3
用1完成
在这里4
在这里5
在这里
完成2
在这里7
用6完成
用7完成
用4完成
用5英镑完成
[2, 3, 4, 5, 6, 7, 8, 9]