Elixir - DailyTrip [001.4] Processes and Messaging

We'll start a new project:

mix new ping_pong
cd ping_pong

test/ping_pong_test.exs

defmodule PingPongTest do
  use ExUnit.Case
  doctest PingPong

  test "it responds to a pong with a ping" do
    ping = spawn(Ping, :start, [])
    send(ping, {:pong, self()})
    assert_receive {:ping, ^ping}
  end

  test "it responds to two message" do
    ping = spawn(Ping, :start, [])
    send(ping, {:pong, self()})
    assert_receive {:ping, ^ping}
    send(ping, {:pong, self()})
    assert_receive {:ping, ^ping}
  end
end

end

lib/ping.ex

defmodule Ping do
  def start do
    loop()
  end

  def loop do
    receive do
      # {:pong, from} -> send(from, {:ping, self()})
      {:pong, from} ->
        IO.puts("ping ->")
        :timer.sleep(500)
        send(from, {:ping, self()})

      {:ping, from} ->
        IO.puts("     <- pong")
        :timer.sleep(500)
        send(from, {:pong, self()})
    end

    loop()
  end
end

iex -S mix

iex(1)> ping = spawn(Ping, :start, [])
#PID<0.108.0>
iex(2)> pong = spawn(Ping, :start, [])
#PID<0.110.0>
iex(3)> send(ping, {:pong, pong})
ping ->
{:pong, #PID<0.110.0>}
            <- pong
ping ->
            <- pong
ping ->
            <- pong
ping ->
            <- pong
...

你可能感兴趣的:(Elixir - DailyTrip [001.4] Processes and Messaging)