Skip to content

Instantly share code, notes, and snippets.

@kachayev
Created February 6, 2013 12:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kachayev/4722186 to your computer and use it in GitHub Desktop.
Save kachayev/4722186 to your computer and use it in GitHub Desktop.
Simplest ping-pong example of Scala Actors
import scala.actors.Actor
import scala.actors.Actor._
case object Ping
case object Pong
case object Stop
class Ping(count: Int, pong: Actor) extends Actor {
def act() {
var pingsLeft = count - 1
pong ! Ping
loop {
react {
case Pong =>
if (pingsLeft % 1000 == 0)
Console.println("Ping: pong")
if (pingsLeft > 0) {
pong ! Ping
pingsLeft -= 1
} else {
Console.println("Ping: stop")
pong ! Stop
exit()
}
}
}
}
}
class Pong extends Actor {
def act() {
var pongCount = 0
loop {
react {
case Ping =>
if (pongCount % 1000 == 0)
Console.println("Pong: ping "+pongCount)
sender ! Pong
pongCount = pongCount + 1
case Stop =>
Console.println("Pong: stop")
exit()
}
}
}
}
object pingpong extends Application {
val pong = new Pong
val ping = new Ping(100000, pong)
ping.start
pong.start
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment