読者です 読者をやめる 読者になる 読者になる

ピンポン

Scala Erlang

Erlangにも、Scalaにも、concurrent programmingに関するチュートリアルがあるが、この分野ではErlangの方がきれいに書けるような気がするな。上がErlang、下がScala

-module(pingpong).
-export([start/0, ping/1, pong/0]).

ping(0) ->
    pong ! finished,
    io:format("ping finished~n");
ping(N) ->
    io:format("Ping ~p~n", [N]),
    pong ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n")
    end,
    ping(N - 1).

pong() ->
    receive
        finished ->
            io:format("pong finished~n");
        {ping, Ping_PID} ->
            io:format("Pong received ping~n"),
            Ping_PID ! pong,
            pong()
    end.

start() ->
    register(pong, spawn(pingpong, pong, [])),
    spawn(pingpong, ping, [3]).
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 left = count
    while (true) {
      pong ! Ping
      receive {
        case Pong =>
          println("Ping received pong")
        left -= 1
        if (left <= 0) {
          pong ! Stop;
          println("ping finished")
          exit()
        }
      }
    }
  }
}

class Pong extends Actor {
  def act() {
    while (true) {
      receive {
        case Ping =>
          println("Pong received ping")
        sender ! Pong
        case Stop =>
          println("pong finished")
          exit()
      }
    }
  }
}

object pingpong2 extends Application {
  val pong = new Pong
  val ping = new Ping(3, pong)
  ping.start
  pong.start
}