我是GPARS库的新手,目前正在我们的软件中实现它。
使用它而不是像
这样的常规groovy方法,对我来说没有问题[..].each{..}
->
[..].eachParallel{..}
但我想知道如何并行化两个返回值的任务。
没有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完成?
答案 0 :(得分:7)
您可以使用Dataflow:
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()
答案 1 :(得分: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() }
}