Skip to content

Instantly share code, notes, and snippets.

@sortega
Created August 14, 2015 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sortega/9e378695474d2f27d03d to your computer and use it in GitHub Desktop.
Save sortega/9e378695474d2f27d03d to your computer and use it in GitHub Desktop.
Naïve parallelization of the Eratosthenes sieve using Akka
import akka.actor._
object SimpleSieve extends App {
val MaxNumber = 500000
case object NoMoreCandidates
class Filter extends Actor {
private var prime: Int = _
override def receive: Receive = {
case NoMoreCandidates =>
println("No more candidates")
println(s"Spent just ${System.currentTimeMillis() - start} millis")
System.exit(0)
case firstCandidate: Int =>
prime = firstCandidate
println(s"$prime found")
context.become(filtering(context.actorOf(Props[Filter])))
}
private def filtering(successor: ActorRef): Receive = {
case candidate: Int if candidate % prime == 0 => // Drop candidate
case other => successor ! other
}
}
val start = System.currentTimeMillis()
val system = ActorSystem("sieve")
val sieve = system.actorOf(Props[Filter])
(2 to MaxNumber).foreach(sieve ! _)
sieve ! NoMoreCandidates
system.awaitTermination()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment