如何等待Elixir衍生过程像Ruby的Thread#join一样结束

Tsu*_*omu 2 ruby multithreading elixir

我有以下Ruby代码:

t = Thread.new do
  sleep(1)
  puts "Finished!"
end

t.join
Run Code Online (Sandbox Code Playgroud)

如何在Elixir中编写等效代码?

我写了以下一篇:

spawn fn ->
  :timer.sleep(1000)
  IO.puts "Finished!"
end

:timer.sleep(1000)
Run Code Online (Sandbox Code Playgroud)

它可以工作,但这不等同于Ruby版本.

Dog*_*ert 12

你可以使用Process.monitor/1receive为此:

pid = spawn(fn ->
  :timer.sleep(1000)
  IO.puts "Finished!"
end)

# Start monitoring `pid`
ref = Process.monitor(pid)

# Wait until the process monitored by `ref` is down.
receive do
  {:DOWN, ^ref, _, _, _} ->
    IO.puts "Process #{inspect(pid)} is down"
end
Run Code Online (Sandbox Code Playgroud)

输出:

Finished!
Process #PID<0.73.0> is dead
Run Code Online (Sandbox Code Playgroud)

Process #PID<0.73.0> is dead之后印刷Finished!.

  • 值得一提的是,它仍然不是Ruby版本的等价物,也没有,因为线程和进程之间存在显着差异. (2认同)

Mar*_*lin 7

而不是瞄准尽可能等同的东西,这就是我认为对于"运行后台进程睡眠一秒,并且在完成之前不退出脚本"的问题的更惯用的方法.

Task.async(fn -> :timer.sleep(1000) end)
|> Task.await
Run Code Online (Sandbox Code Playgroud)