Concurrency 与withPool并行

Concurrency 与withPool并行,concurrency,groovy,parallel-processing,gpars,Concurrency,Groovy,Parallel Processing,Gpars,我找到了一个关于如何在池中使用的示例。它说我只需要将单词Parallel添加到Groovy的方法中,比如collect、find、each,将其放入withPool,然后它并行执行代码 import static groovyx.gpars.GParsPool.withPool list = 1..1000000 withPool{ squares = list.collectParallel { it * it} } println squares 是否有机会检查它是否真的是平行

我找到了一个关于如何在池中使用
的示例。它说我只需要将单词
Parallel
添加到Groovy的方法中,比如
collect、find、each
,将其放入
withPool
,然后它并行执行代码

import static groovyx.gpars.GParsPool.withPool

list = 1..1000000

withPool{
    squares = list.collectParallel { it * it}
}
println squares
是否有机会检查它是否真的是平行的?
我用相同的代码尝试了一个基准测试,但采用了顺序方式
平行方式要慢得多。

不确定你所说的“但顺序和平行方式要慢得多”是什么意思

这将并行运行,但对于这个过于简单的示例,将作业发送到其他处理器和处理结果排序的额外成本可能会比只乘以一些数字花费更长的时间

对于显示其工作原理的简单示例,您可以执行以下操作:

import static groovyx.gpars.GParsPool.withPool

list = [ 2, 2, 2, 2, 2 ]

withPool{
    result = list.collectParallel {
        Thread.sleep( it * 1000 )
        it
    }
}
println result
因此,结果应该是
[2,2,2,2,2]
,但是
collectParallel
应该在串行
collect
版本的10秒内完成


显然,这取决于您拥有多个核心;-)

我的描述有所改进。您可以查看Windows任务管理器的CPU使用情况。所以,当并行处理繁重的任务时,CPU使用率可以达到100%。非常感谢!这对我帮助很大!