2016-05-08 52 views
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」?

回答

1

您看到的值是TwoPs.create_ps/0的返回值,在這種情況下是第二個接收塊返回的值。如果你要同時打印接收到的值,你應該明確地與IO.puts/2打印出來:

defmodule TwoPs do 
    def echo(pid) do 
    receive do 
     msg -> 
     IO.puts("Received #{msg}") 
     send pid, {:ok, "Hello #{msg}"} 
    end 
    end 

    def create_ps() do 
    p1 = spawn(TwoPs, :echo, [self]) 
    p2 = spawn(TwoPs, :echo, [self]) 

    send p1, "World" 
    receive do 
     {:ok, msg} -> IO.puts "#{msg}" 
    end 

    send p2, "Bob" 
    receive do 
     {:ok, msg} -> IO.puts "#{msg}" 
    end 
    end 
end 

測試:

iex(1)> TwoPs.create_ps 
Received World 
Hello World 
Received Bob 
Hello Bob 
:ok 
+0

謝謝。驚人的快速反應。完全錯過了。愚蠢的錯誤在我身上 – sat

相關問題