Skip to content

Instantly share code, notes, and snippets.

@tiagodavi
Last active October 20, 2015 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiagodavi/65972bf781ac6130d5d4 to your computer and use it in GitHub Desktop.
Save tiagodavi/65972bf781ac6130d5d4 to your computer and use it in GitHub Desktop.
A code that creates n processes
# How does it work?
# $ elixir -r chain.exs -e "Chain.run(1000)" to have one thousand processes.
defmodule Chain do
def counter(next_pid) do
receive do
n -> send next_pid, n + 1
end
end
def create_processes(n) do
last = Enum.reduce 1..n, self,
fn (_,send_to) ->
spawn(Chain, :counter, [send_to])
end
send last, 0
receive do
final_answer when is_integer(final_answer) -> "Result is #{inspect(final_answer)}"
end
end
def run(n) do
IO.puts inspect :timer.tc(Chain, :create_processes, [n])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment