【问题标题】:Non anonymous function inside spawn is not executing asynchronouslyspawn 中的非匿名函数未异步执行
【发布时间】: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


    【解决方案1】:

    使用spawn(&amp;fun/0)

    您现在所做的是评估fun 并将结果传递给spawn。这就是为什么它等待fun 完成然后发送:ok(这是来自IO.puts("sleep over") 的响应-fun 中的最后一条语句)来生成。 这就是错误:erlang.spawn(:ok) 的含义。

    您必须捕获该函数并将其作为参数传递给spawn 继续阅读Function Capturing

    【讨论】:

      猜你喜欢
      • 2022-06-10
      • 1970-01-01
      • 2019-01-10
      • 2022-11-16
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多