Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Prime sieves in Scala with Akka Actors
import akka.actor._
import akka.actor.Actor._
case class sieve(n: Int)
case class finish(n: Int)
class SieveAkka(val p: Int) extends Actor {
var next: ActorRef = null
def _sieve(n: Int) = {
if (isPrime(n)) {
if (next != null) {
next ! sieve(n)
} else {
next = actorOf(new SieveAkka(n))
next.start
// println(n + " is prime")
}
}
}
private def isPrime(n: Int): Boolean = {
val d = n / p
val r = n - d * p
if (r != 0) true else false
}
def receive = {
case sieve(n: Int) => _sieve(n)
case finish(n: Int) => {
if (next != null) {
next ! finish(n)
} else {
val time = System.currentTimeMillis - MainAkka.start
println(n + "," + time)
// System.exit(0)
}
}
}
}
object GeneratorAkka {
def generate(n: Int): Unit = {
val p2 = actorOf(new SieveAkka(2))
p2.start
for (i <- 3 to n) {
p2 ! sieve(i)
}
p2 ! finish(n)
}
}
object MainAkka {
var start = System.currentTimeMillis
def main(args: Array[String]): Unit = {
for (i <- 10 to 10) {
start = System.currentTimeMillis
GeneratorAkka.generate(i * 20000)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment