how to make the program pause when actor is running

105 views Asked by At

For example

import scala.actors.Actor
import scala.actors.Actor._

object Main {
  class Pong extends Actor {
    def act() {
      var pongCount = 0
      while (true) {
        receive {
          case "Ping" =>
            if (pongCount % 1000 == 0)
              Console.println("Pong: ping "+pongCount)
            sender ! "Pong"
            pongCount = pongCount + 1
          case "Stop" =>
            Console.println("Pong: stop")
            exit()
        }
      }
    }
  }

  class Ping(count: Int, pong: Actor) extends Actor {
    def act() {
      var pingsLeft = count - 1
      pong ! "Ping"
      while (true) {
        receive {
          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()
            }
        }
      }
    }
  }

  def main(args: Array[String]): Unit = {
    val pong = new Pong
    val ping = new Ping(100000, pong)
    ping.start
    pong.start
    println("???")
  }

}

I try to print "???" after the two actors call exit(), but now it is printed before "Ping: Stop" and "Pong stop"

I have try have a flag in the actor, flag is false while actor is running, and flag is true when actor stops, and in the main func, there is a while loop, such as while (actor.flag == false) {}, but it doesn't works, it is a endless loop:-/

So, please give me some advice.

1

There are 1 answers

2
Dmitry  Meshkov On BEST ANSWER

If you need synchronous calls in akka, use ask pattern. Like

Await.result(ping ? "ping")  

Also, you'd better use actor system to create actors.

import akka.actor.{ActorRef, Props, Actor, ActorSystem}
import akka.pattern.ask
import akka.util.Timeout

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object Test extends App {

  implicit val timeout = Timeout(3 second)
  val system = ActorSystem("ActorSystem")

  class Pong extends Actor {
    def receive: Receive = {
      case "Ping" =>
        println("ping")
        context.stop(self)
    }
  }

  lazy val pong = system.actorOf(Props(new Pong), "Pong")

  val x = pong.ask("Ping")
  val res = Await.result(x, timeout.duration)
  println("????")
  system.shutdown()

}