【问题标题】:makeConcurrent dosen't seem to work in GparsmakeConcurrent 似乎在 Gpars 中不起作用
【发布时间】:2015-05-20 22:59:30
【问题描述】:

以下程序应该返回具有空值的行列表。

import groovyx.gpars.GParsPool
import groovyx.gpars.ParallelEnhancer
import org.apache.commons.lang.RandomStringUtils
import groovyx.gprof.*
import static java.lang.Runtime.*;

def rows = []
def list = []

String charset = (('A'..'Z') + ('0'..'9')).join()
Integer length = 9

for (i in 0..1024) {
    rows[i] = RandomStringUtils.random(length, charset.toCharArray())
}

parallelResult = []
// Parallel execution

GParsPool.withPool(8) {
    parallelResult.makeConcurrent()
    rows.eachParallel {
        if (it[0] != null) {
            parallelResult.push(it)
        }
    }
    parallelResult.makeSequential()
}

// Sequential execution 
sequentialResult = []
rows.each {
    if (it[0] != null) {
        sequentialResult.push(it)
    }
}

assert parallelResult.size == sequentialResult.size

有时,结果并不相同。这可能是由于 makeParallel 的一些问题。如果不是 makeParallel,我如何使用 GPars 创建并发列表?

【问题讨论】:

    标签: multithreading groovy thread-safety threadpool gpars


    【解决方案1】:

    我怀疑您在 parallelResult 上引入了竞争条件。 makeConcurrent() 不会阻止集合上的竞争条件,它只会改变 each()、collect() 等方法的行为。

    如果您想使用累加器保留当前设计,则需要对其进行同步或使用代理。但是,在我看来,您应该考虑使用更实用的方法。也许像“parallelResult = rows.findAllParallel{it[0]!=null}”

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 1970-01-01
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多