【发布时间】:2018-10-06 19:54:39
【问题描述】:
这是我的代码:
defmodule Test do
def fun() do
Process.sleep(10000)
IO.puts "sleep over"
end
def dummy(:b) do
spawn(fun())
end
def dummy(:a) do
spawn(Test,:fun,[])
end
def dummy() do
spawn(fn -> Process.sleep(10000)
IO.puts "sleep over"
end)
IO.puts "process started"
end
end
在运行此代码并执行各种虚拟函数时,我得到了以下输出:
iex(1)> c("test.exs")
[Test]
iex(2)> Test.dummy
process started
:ok
sleep over
iex(3)> Test.dummy :
** (SyntaxError) iex:3: unexpected token: ":" (column 12, codepoint U+003A)
iex(3)> Test.dummy :a
#PID<0.111.0>
iex(4)>
nil
iex(5)>
nil
sleep over
iex(6)> Test.dummy :b
sleep over
** (ArgumentError) argument error
:erlang.spawn(:ok)
iex(6)>
我主要关心的是为什么当我们使用 spawn/1 而不是匿名函数时,它不会异步执行该函数,而是等待该函数执行,而在 spawn 中的其他两个函数中,它是异步执行的(如我所料)。
【问题讨论】:
标签: elixir