我有以下Ruby代码:
t = Thread.new do
sleep(1)
puts "Finished!"
end
t.join
如何在Elixir中编写等效代码?
我写了以下内容:
spawn fn ->
:timer.sleep(1000)
IO.puts "Finished!"
end
:timer.sleep(1000)
它可以工作,但这不等同于Ruby版本。
答案 0 :(得分:11)
您可以使用Process.monitor/1
和receive
:
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
输出:
Finished!
Process #PID<0.73.0> is dead
Process #PID<0.73.0> is dead
在Finished!
之后打印。
答案 1 :(得分:7)
不是针对尽可能等同的东西,而是我认为对于问题的更惯用的方法是运行一个睡眠一秒钟的后台进程,并且#&# 39;退出脚本直到完成。&#34;
Task.async(fn -> :timer.sleep(1000) end)
|> Task.await
答案 2 :(得分:0)
我认为这可以为您提供一些线索:
# save in a spawner.ex file
for _ <- 1..10 do
spawn(fn ->
pid = self()
ms = Enum.random(1..1000)
:timer.sleep(ms)
IO.puts "#{inspect(pid)} finished in #{ms}ms"
end)
end
:timer.sleep(2000)
IO.puts "Jobs done, thanks!"
它将输出类似的内容
iex(12)> c "./spawner.ex"
#PID<0.179.0> finished in 21ms
#PID<0.180.0> finished in 102ms
#PID<0.185.0> finished in 113ms
#PID<0.183.0> finished in 273ms
#PID<0.178.0> finished in 400ms
#PID<0.182.0> finished in 671ms
#PID<0.184.0> finished in 751ms
#PID<0.186.0> finished in 933ms
#PID<0.187.0> finished in 936ms
#PID<0.181.0> finished in 985ms
Jobs done, thanks!
[]
iex(13)>