Added Routing.Broadcast message and handling to be able to broadcast a message to all the actors a load-balancer represents

This commit is contained in:
Jonas Bonér 2011-04-01 15:33:46 +02:00
parent 384332da39
commit d97b8fbd9c
5 changed files with 49 additions and 44 deletions

View file

@ -4,9 +4,10 @@
package akka.tutorial.sbt.pi
import akka.actor.{Actor, ActorRef}
import akka.actor.{Actor, ActorRef, PoisonPill}
import Actor._
import akka.routing.{Routing, CyclicIterator}
import Routing._
import akka.event.EventHandler
import akka.dispatch.Dispatchers
@ -17,38 +18,21 @@ object Main extends App {
Pi.calculate
}
/*
Pi estimate: 3.1415926435897883
=== 8 workers (with custom dispatcher 4/4)
Calculation time: 5163 millis
=== 8 workers (with default dispatcher)
Calculation time: 6789 millis
=== 4 workers
Calculation time: 5438 millis
=== 2 workers
Calculation time: 6002 millis
=== 1 workers
Calculation time: 8173 millis
*/
object Pi {
val nrOfWorkers = 4
val nrOfMessages = 10000
val nrOfWorkers = 4
val nrOfMessages = 10000
val nrOfElements = 10000
// ===== Messages =====
sealed trait PiMessage
case class Calculate(nrOfMessages: Int, nrOfElements: Int) extends PiMessage
case class Work(arg: Int, fun: (Int) => Double) extends PiMessage
case class Result(value: Double) extends PiMessage
// ===== Worker =====
class Worker extends Actor {
def receive = {
case Work(arg, fun) => self.reply(Result(fun(arg)))
case Work(arg, fun) => self reply Result(fun(arg))
}
}
@ -68,19 +52,20 @@ object Pi {
// wrap them with a load-balancing router
val router = Routing.loadBalancerActor(CyclicIterator(workers)).start
// define the work
val algorithm = (i: Int) => {
val range = (i * nrOfElements) to ((i + 1) * nrOfElements - 1)
val results = for (j <- range) yield (4 * math.pow(-1, j) / (2 * j + 1))
results.sum
}
def receive = {
case Calculate(nrOfMessages, nrOfElements) =>
// define the work
val fun = (i: Int) => {
val range = (i * nrOfElements) to ((i + 1) * nrOfElements - 1)
val results = for (j <- range) yield (4 * math.pow(-1, j) / (2 * j + 1))
results.sum
}
// schedule work
for (arg <- 0 until nrOfMessages) router ! Work(arg, fun)
for (arg <- 0 until nrOfMessages) router ! Work(arg, algorithm)
// send a PoisonPill to all workers telling them to shut down themselves
router broadcast PoisonPill
router ! Broadcast(PoisonPill)
case Result(value) =>
pi += value
@ -92,12 +77,12 @@ object Pi {
override def postStop = {
EventHandler.info(this, "\n\tPi estimate: \t\t%s\n\tCalculation time: \t%s millis".format(pi, (now - start)))
latch.nrOfResultsDown
latch.countDown
}
}
def calculate = {
val latch = new nrOfResultsDownLatch(1)
val latch = new CountDownLatch(1)
// create the master
val master = actorOf(new Master(latch)).start