/bench/scala/PingPongEx.scala

http://github.com/kilim/kilim · Scala · 86 lines · 68 code · 8 blank · 10 comment · 2 complexity · 4f8471c7da0ae977f30d225fbe667224 MD5 · raw file

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