Elixir “Losing” Processes

那年仲夏 提交于 2019-12-12 04:22:42

问题


If I create a file loop.exs:

Enum.each(1..40000, fn (n) -> spawn fn -> IO.puts(n) end end)

And run it, counting the lines of output:

elixir loop.exs | wc -l

And on subsequent runs, I may see the expected 40000 lines, but I might see less. In my tests, I've seen 39752, 39934, 39673, etc. This suggests to me that certain processes aren't getting to call IO.puts, so what is happening to them, why aren't I warned they've gone missing, and what am I doing wrong that is making this happen?


回答1:


The problem is that the script is exiting as soon as it's done evaluating the expressions at the root level. Since spawning processes is asynchronous, Elixir quits as soon as it's done spawning the 40,000th process. The number of lines you're seeing is the number of processes that finished executing IO.puts before the 40,000th process was spawned. You can verify this by adding a little :timer.sleep/1 call at the end:

Enum.each(1..40000, fn (n) -> spawn fn -> IO.puts(n) end end)
:timer.sleep(500)

With this, I always get 40k lines of output. (This number will be less if the last IO.puts isn't executed within 500 milliseconds of the last process being spawned.)



来源:https://stackoverflow.com/questions/40311041/elixir-losing-processes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!