May 2018
Intermediate to advanced
412 pages
9h 3m
English
At the start of the chapter, I somewhat cavalierly said 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 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.
| 1: | defmodule Chain do |
| - | def counter(next_pid) do |
| - | receive do |
| - | n -> |
| 5: | send next_pid, n + 1 |
| - | end |
| - | end |
| - | |
| - | def create_processes(n) do |
| 10: | code_to_run = fn (_,send_to) -> |
| - | spawn(Chain, :counter, [send_to]) |
| - | end |
| - | |
| - | last = Enum.reduce(1..n, self(), code_to_run) |
| 15: | |
| - | send(last, 0) # start the ... |
Read now
Unlock full access