groovyparallel-processinggpars

Groovy/Grails GPARS: How to execute 2 calculations parallel?


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?


Solution

  • 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()