7
votes

I'm new to the GPARS-library and implementing it in our software at the moment.

It's no problem for me to use it instead of the normal groovy-methods like

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

But I'm wondering how to parallelize 2 tasks which are returning a value.

Without GPARS I would do it this way:

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

But (how) can this be done with the GparsPool?

2

2 Answers

7
votes

You could use 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

Alternative for 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
votes
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() }
}