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.
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: | send last, 0 # start the count by sending a zero to the last ... |
Get Programming Elixir 1.2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.