我在这里找到了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()
? 最佳答案
我对GPar不太熟悉,但是您提供的链接说这是一种Divide-and-Conquer算法,并在稍后澄清了更多隐含的内容,并说明forkOffChild()
不会等待-而是getChildrenResults()
可以。
如果您对此较为熟悉,则可能会在同一页面中发现更容易理解的替代方法,该方法使用Java风格。childrenResults
会导致调用方法 getChildrenResults()
,这是“Fork / Join”中的“join”,它等待所有子项完成,然后返回一个列表,列出它们的结果(或重新抛出子项可能抛出的任何异常)。0
只是总和的初始值。如果childrenResult
为空,那么这就是count
的总和:
groovy:000> [].sum(1)
===> 1
groovy:000> [1].sum(1)
===> 2
关于groovy - 具有GPar的Fork/Join示例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14544040/