Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

Elixir "Losing" Processes

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...