7.8 Classic Examples - Reference Documentation
Authors: The Whole GPars Gang
Version: 1.0-SNAPSHOT
7.8 Classic Examples
The Sieve of Eratosthenes implementation using dataflow tasks
import groovyx.gpars.dataflow.DataflowQueue import static groovyx.gpars.dataflow.Dataflow.task/** * Demonstrates concurrent implementation of the Sieve of Eratosthenes using dataflow tasks */final int requestedPrimeNumberCount = 1000final DataflowQueue initialChannel = new DataflowQueue()/** * Generating candidate numbers */ task { (2..10000).each { initialChannel << it } }/** * Chain a new filter for a particular prime number to the end of the Sieve * @param inChannel The current end channel to consume * @param prime The prime number to divide future prime candidates with * @return A new channel ending the whole chain */ def filter(inChannel, int prime) { def outChannel = new DataflowQueue() task { while (true) { def number = inChannel.val if (number % prime != 0) { outChannel << number } } } return outChannel }/** * Consume Sieve output and add additional filters for all found primes */ def currentOutput = initialChannel requestedPrimeNumberCount.times { int prime = currentOutput.val println "Found: $prime" currentOutput = filter(currentOutput, prime) }
The Sieve of Eratosthenes implementation using a combination of dataflow tasks and operators
import groovyx.gpars.dataflow.DataflowQueue import static groovyx.gpars.dataflow.Dataflow.operator import static groovyx.gpars.dataflow.Dataflow.task /** * Demonstrates concurrent implementation of the Sieve of Eratosthenes using dataflow tasks and operators */ final int requestedPrimeNumberCount = 100 final DataflowQueue initialChannel = new DataflowQueue() /** * Generating candidate numbers */ task { (2..1000).each { initialChannel << it } } /** * Chain a new filter for a particular prime number to the end of the Sieve * @param inChannel The current end channel to consume * @param prime The prime number to divide future prime candidates with * @return A new channel ending the whole chain */ def filter(inChannel, int prime) { def outChannel = new DataflowQueue() operator([inputs: [inChannel], outputs: [outChannel]]) { if (it % prime != 0) { bindOutput it } } return outChannel } /** * Consume Sieve output and add additional filters for all found primes */ def currentOutput = initialChannel requestedPrimeNumberCount.times { int prime = currentOutput.val println "Found: $prime" currentOutput = filter(currentOutput, prime) }