我试图了解这段Elixir代码中发生了什么。我们生成了两个进程,然后生成的进程将消息回送给发送方,但我只在iex中看到一条消息。怎么了?
<html>
<head></head>
<body>
<?php include 'file.php';?>
<form action="" method="POST">
<b>Busque Jรก</b>
<input type="text" name="prestador" placeholder="prestador">
<input type="text" name="cidade" placeholder="cidade">
<input type="submit">
</form>
</body>
</html>
iex中的输出总是&#34; Hello Bob&#34;
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
为什么我们不看&#34; Hello World&#34;?
答案 0 :(得分: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