October 2014
Intermediate to advanced
280 pages
7h 20m
English
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 -> |
| 5 | 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 ... |
Read now
Unlock full access