首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用GPars的分叉/联接示例

使用GPars的分叉/联接示例
EN

Stack Overflow用户
提问于 2013-01-27 11:09:53
回答 1查看 1.3K关注 0票数 3

我在这里找到了GPars中的fork/join示例:Fork/Join

代码语言:javascript
复制
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
        }
    }"""
}

它可以工作并返回正确的文件数,但不幸的是我不理解这一行:

代码语言:javascript
复制
return count + (childrenResults.sum(0))

countchildrenResult的确切工作原理

为什么要将0作为参数传递给sum()

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-27 19:30:14

我对GPars不是很熟悉,但是您提供的链接说它是一种Divide-and-Conquer算法,并在后面解释了更多隐含的含义,解释说forkOffChild()不等待--相反,getChildrenResults()等待。

如果您更熟悉的话,您可能会发现在同一页面中提供的替代方法更容易理解,因为它使用了更多的Java风格。

childrenResults导致调用方法getChildrenResults(),这是"Fork/Join“中的"join”,它等待所有的子节点完成,然后返回一个包含它们的结果的列表(或者重新抛出一个子节点可能抛出的任何异常)。

0只是总和的初始值。如果childrenResult为空,则对count求和

代码语言:javascript
复制
groovy:000> [].sum(1)
===> 1
groovy:000> [1].sum(1)
===> 2
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14544040

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档