Elixir进程未收到消息 [英] Elixir process not receiving message

查看:89
本文介绍了Elixir进程未收到消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有时候我只有一行输出

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

或多行,然后停止

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?

推荐答案

这是因为Erlang VM在执行<$ c之后退出$ c> Pingpong.start ,因为主进程没有任何代码可执行。如果添加:timer.sleep(:infinity)以确保主进程没有退出,则应该看到 ping pong 会永远连续打印:

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)"

这篇关于Elixir进程未收到消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆