Process Overhead
Learn about the process and its creation in Elixir.
At the start of the chapter, we said that Elixir processes were very low overhead. Now, it’s time to back that up. Let’s write some code that creates n processes. The first will send a number to the second. It’ll increment that number and pass it to the third. This’ll continue until we get to the last process, which will pass the number back to the top level.
Run the example code in the terminal below.
defmodule Chain do def counter(next_pid) do receive do n -> send next_pid, n + 1 end end def create_processes(n) do code_to_run = fn (_,send_to) -> spawn(Chain, :counter, [send_to]) end last = Enum.reduce(1..n, self(), code_to_run) send(last, 0) # start the count by sending a zero to the last process receive do # and wait for the result to come back to us final_answer when is_integer(final_answer) -> "Result is #{inspect(final_answer)}" end end def run(n) do :timer.tc(Chain, :create_processes, [n]) |> IO.inspect end end
Code explanation
The counter
function on line 2 runs in separate processes. It’s passed the PID of the next process in the chain. When it receives a number, it increments it and sends it on to that next process.
The create_processes
function is probably the densest piece of Elixir we’ve encountered so far. Let’s break it down:
-
It’s passed the number of processes to create. Each process has to be passed the PID of the previous process so that it knows who to send the updated number to.
-
The code that creates each process is defined in a one-line anonymous function, which is assigned to the variable
code_to_run
. The function takes two parameters because ...