Skip to content

Instantly share code, notes, and snippets.

@vaclav
Last active August 29, 2015 13:59
Show Gist options
  • Save vaclav/10485027 to your computer and use it in GitHub Desktop.
Save vaclav/10485027 to your computer and use it in GitHub Desktop.
Inspired by https://gist.github.com/timyates/10474027, just using static and dynamic dispatch actors instead
import groovy.transform.*
import groovyx.gpars.actor.*
import groovyx.gpars.group.*
@Immutable class Calculate {}
@Immutable class Work { int start, nrOfElements }
@Immutable class Result { double value }
@Immutable class PiApproximation { double pi ; long duration }
double calculatePiFor( int start, int nrOfElements ) {
((start * nrOfElements)..((start + 1) * nrOfElements - 1)).inject( 0.0 ) { acc, i ->
acc += 4.0 * (1 - (i % 2) * 2) / (2 * i + 1)
}
}
def group = new DefaultPGroup()
def listener = group.staticMessageHandler {
println "Pi approx $it.pi in $it.duration"
terminate()
}
int nrOfWorkers = 4
int nrOfMessages = 1000
int nrOfElements = 1000
def workers = (1..nrOfWorkers).collect {
group.staticMessageHandler {
reply new Result( calculatePiFor( it.start, it.nrOfElements ) )
}
}
double pi = 0.0
int nrOfResults = 0
long start = System.currentTimeMillis()
def master = group.messageHandler {
when{Calculate msg ->
nrOfMessages.times { i -> workers[ i % nrOfWorkers ].send( new Work( i, nrOfElements ) ) }}
when{Result msg ->
pi += msg.value
if( ++nrOfResults >= nrOfMessages ) {
listener.send( new PiApproximation( pi, System.currentTimeMillis() - start ) )
workers*.terminate()
terminate()
}
}
}
master << new Calculate()
master.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment