【问题标题】:Elixir process not receiving messageElixir 进程未收到消息
【发布时间】:2017-01-21 17:12:22
【问题描述】:

我是 Elixir 的新手,目前正在学习流程。在实践中,我编写了一个 ping pong 程序,从 2 个进程中打印“ping”和“pong”。进程在收到 1 或 2 条消息后总是死亡。这是我的代码

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

有时我只得到一行输出

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

或多行然后停止

ping
pong
ping
pong
ping
pong

但我认为它应该持续打印输出,直到我停止程序。 上面的代码有什么问题?

【问题讨论】:

    标签: elixir


    【解决方案1】:

    这是因为 Erlang VM 在执行Pingpong.start 后退出,因为主进程没有任何代码可以执行。如果您添加:timer.sleep(:infinity) 以确保主进程不退出,您应该会看到pingpong 被永久连续打印:

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

    【讨论】:

    • :timer.sleep(:infinity) 修复了它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 2014-02-26
    • 1970-01-01
    • 2018-05-15
    • 2014-02-17
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多