O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Process Overhead

At the start of the chapter, I somewhat cavalierly said Elixir processes were very low overhead. Now it is time to back that up. Let’s write some code that creates n processes. The first will send a number to the second. It will increment that number and pass it to the third. This will continue until we get to the last process, which will pass the number back to the top level.

spawn/chain.exs
Line 1 
defmodule​ Chain ​do
def​ counter(next_pid) ​do
receive​ ​do
n ->
send next_pid, n + 1
end
end
def​ create_processes(n) ​do
10 
last = Enum.reduce 1..n, self,
fn​ (_,send_to) ->
spawn(Chain, :counter, [send_to])
end
15 
# start the count by sending
send last, 0
# and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required