7

我是 GPARS 库的新手,目前在我们的软件中实现它。

使用它代替普通的常规方法对我来说没问题

[..].each{..} 
-> 
[..].eachParallel{..}

但我想知道如何并行化 2 个返回值的任务。

如果没有 GPARS,我会这样做:

List<Thread> threads = []
def forecastData
def actualData  
threads.add(Thread.start {
    forecastData = cosmoSegmentationService.getForecastSegmentCharacteristics(dataset, planPeriod, thruPeriod)
})

threads.add(Thread.start {
    actualData = cosmoSegmentationService.getMeasuredSegmentCharacteristics(dataset, fromPeriod, thruPeriodActual)
})

threads*.join()

// merge both datasets
def data = actualData + forecastData

但是(如何)使用 GparsPool 可以做到这一点?

4

2 回答 2

7

您可以使用数据流:

import groovyx.gpars.dataflow.*
import static groovyx.gpars.dataflow.Dataflow.task

def forecastData = new DataflowVariable()
def actualData = new DataflowVariable()
def result = new DataflowVariable()

task {
  forecastData << cosmoSegmentationService.getForecastSegmentCharacteristics( dataset, planPeriod, thruPeriod )
}

task {
  actualData << cosmoSegmentationService.getMeasuredSegmentCharacteristics( dataset, fromPeriod, thruPeriodActual )
}

task {
  result << forecastData.val + actualData.val
}

println result.val

GPars 0.9 的替代方案:

import static groovyx.gpars.GParsPool.withPool

def getForecast = {
  cosmoSegmentationService.getForecastSegmentCharacteristics( dataset, planPeriod, }

def getActual = {
  cosmoSegmentationService.getMeasuredSegmentCharacteristics( dataset, fromPeriod, thruPeriodActual )
}

def results = withPool {
  [ getForecast.callAsync(), getActual.callAsync() ]
}

println results*.get().sum()
于 2012-12-07T09:54:15.763 回答
1
import groovyx.gpars.GParsPool    

List todoList =[]

todoList.add {
    for(int i1: 1..100){
        println "task 1:" +i1
        sleep(300)
    }
}
todoList.add {
    for(int i2: 101..200){
        println "task 2:" +i2
        sleep(300)
    }
}

GParsPool.withPool(2) {
    todoList.collectParallel { closure->closure() }
}
于 2015-06-07T11:21:50.727 回答