0
我想了解這片Elixir代碼中發生了什麼。我們有兩個進程產生,然後產生的進程回聲消息回發送給發件人,但我只看到一個消息在IEX。怎麼了?爲什麼發件人沒有再收到產生的過程消息?
defmodule TwoPs do
# a simple echo function - take a pid to send message back to
def echo(pid) do
#wait till the spawned process receives a message, turn around and echo it back to the sender
receive do
msg ->
IO.puts("Received #{msg}")
send pid, {:ok, "Hello #{msg}"}
end
end
#spawn's two processes and sends a message to both...expects an echo back from both spawned processes
def create_ps() do
#spawn the two processes
p1 = spawn(TwoPs, :echo, [self])
p2 = spawn(TwoPs, :echo, [self])
#send a message to the first pid
send p1, "World"
#receive message back from spawned child 1
receive do
{:ok, msg} -> "#{msg}"
end
#send a message to the second pid
send p2, "Bob"
#receive message from the spawned child 2
receive do
{:ok, msg} -> "#{msg}"
end
end
end
在IEX的輸出總是 「你好鮑勃」
iex(17)> TwoPs.create_ps
Received World
Received Bob
"Hello Bob"
我們爲什麼不看到 「Hello World」?
謝謝。驚人的快速反應。完全錯過了。愚蠢的錯誤在我身上 – sat