美文网首页
Elixir - DailyTrip [001.4] Proce

Elixir - DailyTrip [001.4] Proce

作者: c8ac4dad76db | 来源:发表于2018-08-11 10:28 被阅读6次

    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] Proce

          本文链接:https://www.haomeiwen.com/subject/udlzvftx.html