[英]Understanding python multiprocessing: does code wait for all process to finish
I have a piece of code which looks as following: 我有一段代码,如下所示:
Data = [1, 2, 3, 4, 5]
def Fn2(obj):
return 2*obj
p = Pool(multiprocessing.cpu_count())
valueList = p.map(Fn2, Data) #---question Line 1
valueList = 2*valueList #--question Line 2
At Line 1
the processors are returning values which gets stored in valueList
. 在
Line 1
,处理器返回的值将存储在valueList
。 I have 8 cores on my computer. 我的计算机上有8个核心。 Initially job gets assigned to all cores.
最初,作业被分配给所有核心。 When let's say out of 8 cores, 5 cores free up.
如果说8个内核中有5个内核可用。 Do the rest of cores jump to
Line 2
or wait for all cores to finish the job and fill up the valueList
and then proceed to Line 2
. 是让其余核心跳到
Line 2
还是等待所有核心完成工作并填写valueList
,然后继续进行Line 2
。
How do I test your answer? 我该如何测试您的答案?
Do the rest of cores jump to Line 2
其余核心是否跳至2号线
No. 没有。
How do I test your answer?
我该如何测试您的答案?
When in doubt about code running in parallel, add sleep
s. 如果对并行运行的代码有疑问,请添加
sleep
。 When in doubt about code in general, add print
s. 一般而言,如果对代码有疑问,请添加
print
。
import multiprocessing
from time import sleep
from multiprocess import Pool
Data = [1, 2, 3, 4, 5]
def Fn2(obj):
print(obj)
sleep(2)
return 2 * obj
p = Pool(multiprocessing.cpu_count())
valueList = p.map(Fn2, Data) # ---question Line 1
print(valueList)
valueList = 2 * valueList # --question Line 2
This gives the following output: 这给出以下输出:
1
2
3
4
5
[2, 4, 6, 8, 10]
And based on the timing it should be clear what's going on. 根据时间安排,应该清楚发生了什么。 Try tweaking the pool size to 3 or something to experiment further.
尝试将池大小调整为3或其他值以进行进一步实验。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.