Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Programming Elixir Process Overhead Demo #119

Closed
2 of 33 tasks
KronicDeth opened this issue May 11, 2019 · 0 comments
Closed
2 of 33 tasks

Programming Elixir Process Overhead Demo #119

KronicDeth opened this issue May 11, 2019 · 0 comments

Comments

@KronicDeth
Copy link
Collaborator

KronicDeth commented May 11, 2019

@pragdave's Programming Elixir was the first Elixir book I read and I still use the Process Overhead demo with 1,000,000 processes to show off that new Elixir programmers shouldn't be worried about making Processes the way they would be with threads. Showing we can compile spawn/chain.ex and run it Chain.run(1_000_000) would be a good MVP target for us.

spawn/chain.ex

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 # 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
    IO.puts inspect :timer.tc(Chain, :create_processes, [n])
  end
end

The book has the 1,000,000 processes run like this: elixir --erl "+P 1000000" -r chain.ex -e "Chain.run(1_000_000)".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant