问题
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