我有以下代码:
parent = self()
spawn_link(fn ->
send(parent, "foo")
send(parent, "bar")
end)
receive do
x -> IO.puts x
end
当我运行此脚本时,“foo”被打印,但不是“bar”。我错过了Elixir流程的基本内容吗?
答案 0 :(得分:3)
一个receive
表达式只处理一条消息。处理这个问题的常用方法是将receive
表达式放在一个函数中,在完成后处理一条消息使它再次递归地调用它自己。
defmodule Receiver do
def loop do
receive do
:exit -> :ok # don't recurse
x ->
IO.puts x
loop
end
end
end
parent = self()
spawn_link(fn ->
send(parent, "foo")
send(parent, "bar")
send(parent, :exit)
end)
Receiver.loop
打印
foo
bar
您还可以{:1}} receive
消息使用:
n
这也打印
defmodule Receiver do
def loop(0), do: :ok
def loop(n) do
receive do
x ->
IO.puts x
loop(n - 1)
end
end
end
parent = self()
spawn_link(fn ->
send(parent, "foo")
send(parent, "bar")
end)
Receiver.loop(2)