Reputation: 20096
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?
Upvotes: 0
Views: 69
Reputation: 222128
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.)
Upvotes: 5