PageRenderTime 6ms CodeModel.GetById 1ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/bench/scala/PingPongEx.scala

http://github.com/kilim/kilim
Scala | 86 lines | 68 code | 8 blank | 10 comment | 2 complexity | 4f8471c7da0ae977f30d225fbe667224 MD5 | raw file
 1package examples.actors
 2
 3import scala.actors.Actor
 4import scala.actors.Actor._
 5
 6abstract class PingMessage
 7case class MsgStart() extends PingMessage
 8case class MsgPingInit(count: int, pong: Pong) extends PingMessage
 9case class MsgSendPing extends PingMessage
10case class MsgPong(sender: Pong) extends PingMessage
11
12abstract class PongMessage
13case class MsgPing(sender: Ping) extends PongMessage
14case class MsgStop() extends PongMessage
15
16object PingPongBench {
17  def main(args : Array[String]): Unit = {
18    val ping = new Ping
19    ping.start
20    val pong = new Pong
21    pong.start
22    ping ! MsgPingInit(100000, pong)
23    ping ! MsgStart
24  }
25}
26
27
28class Ping extends Actor {
29  var beginTime: long = 0;
30  def act(): unit = {
31    loop(0, null)
32  }
33  def loop(pingsLeft: int, pong: Pong): unit = {
34    react {
35      case MsgPingInit(count, pong) => {
36        // System.out.println("Ping: Initializing with count:"+count+":"+pong)
37	beginTime = System.currentTimeMillis();
38        loop(count, pong)
39      }
40      case MsgStart() => {
41//        System.out.println("Ping: starting.")
42        pong ! MsgPing(this)
43        loop(pingsLeft-1, pong)
44      }
45      case MsgSendPing() => {
46        pong ! MsgPing(this)
47        loop(pingsLeft-1, pong)
48      }
49      case MsgPong(pidS) => {
50//        if (pingsLeft % 100 == 0) {
51//          System.out.println("Ping: pong from: "+pidS)
52//        }
53        if (pingsLeft > 0)
54          this ! MsgSendPing()
55        else {
56//          System.out.println("Ping: Stop.")
57	  System.out.println("Elapsed: " + (System.currentTimeMillis() - beginTime));
58          pong ! MsgStop()
59        }
60        loop(pingsLeft, pong)
61      }
62    }
63  }
64}
65
66class Pong extends Actor {
67  def act(): unit = {
68    loop(0)
69  }
70
71  def loop(pongCount: int): unit = {
72    react {
73      case MsgPing(pidPing) => {
74//        if (pongCount % 100 == 0) {
75//          System.out.println("Pong: ping:"+pongCount+" from: "+pidPing)
76//        }
77        pidPing ! MsgPong(this)
78        loop(pongCount+1)
79      }
80      case MsgStop() => {
81//        System.out.println("Pong: Stop.")
82        System.exit(0)
83      }
84    }
85  }
86}