我在这里找到了GPars中的fork/join示例:Fork/Join
import static groovyx.gpars.GParsPool.runForkJoin
import static groovyx.gpars.GParsPool.withPool
withPool() {
println """Number of files: ${
runForkJoin(new File("./src")) {file ->
long count = 0
file.eachFile {
if (it.isDirectory()) {
println "Forking a child task for $it"
forkOffChild(it) //fork a child task
} else {
count++
}
}
return count + (childrenResults.sum(0))
//use results of children tasks to calculate and store own result
}
}"""
}它可以工作并返回正确的文件数,但不幸的是我不理解这一行:
return count + (childrenResults.sum(0))count和childrenResult的确切工作原理
为什么要将0作为参数传递给sum()
发布于 2013-01-27 19:30:14
我对GPars不是很熟悉,但是您提供的链接说它是一种Divide-and-Conquer算法,并在后面解释了更多隐含的含义,解释说forkOffChild()不等待--相反,getChildrenResults()等待。
如果您更熟悉的话,您可能会发现在同一页面中提供的替代方法更容易理解,因为它使用了更多的Java风格。
childrenResults导致调用方法getChildrenResults(),这是"Fork/Join“中的"join”,它等待所有的子节点完成,然后返回一个包含它们的结果的列表(或者重新抛出一个子节点可能抛出的任何异常)。
0只是总和的初始值。如果childrenResult为空,则对count求和
groovy:000> [].sum(1)
===> 1
groovy:000> [1].sum(1)
===> 2https://stackoverflow.com/questions/14544040
复制相似问题