Elixir process not receiving message

此生再无相见时 提交于 2019-12-25 09:03:55

问题


I am new to Elixir and currentlly learning about process. In a practice I wrote a ping pong program that prints "ping" and "pong" from 2 processes. The processes always dead after receiving 1 or 2 messages. Here is my code

defmodule Pingpong do
  def play do
    receive do
     {sender, :ping} ->
        IO.puts  "ping"
        send sender, {self, :pong}
        play
     {sender, :pong} ->
       IO.puts  "pong"
       send sender, {self, :ping}
       play
   end
  end

  def start() do
    a = spawn(Pingpong, :play, [])
    b = spawn(Pingpong, :play, [])
    send a, {b, :ping}
  end
end

Sometimes I got just only one line of output

$ elixir -r pingpong.exs -e "Pingpong.start"
> ping

or multiple lines and then stopped

ping
pong
ping
pong
ping
pong

But I think it should continuously print outputs until I stop the program. What could go wrong with the above code?


回答1:


This is because the Erlang VM exits after executing Pingpong.start as the main process doesn't have any code left to execute. If you add :timer.sleep(:infinity) to make sure the main process doesn't exit, you should see ping and pong being printed continuously forever:

$ elixir -r pingpong.exs -e "Pingpong.start; :timer.sleep(:infinity)"


来源:https://stackoverflow.com/questions/39481242/elixir-process-not-receiving-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!