Created
June 3, 2017 12:09
-
-
Save DarinM223/eabe25910254e290ad5473328c4858cb to your computer and use it in GitHub Desktop.
OTP supervisor Registry example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Otp.Child do | |
@moduledoc """ | |
A simple child process that models a stack. | |
""" | |
use GenServer | |
def start_link(state, opts \\ []) do | |
GenServer.start_link(__MODULE__, state, opts) | |
end | |
def handle_call(:pop, _from, [h | t]) do | |
{:reply, h, t} | |
end | |
def handle_cast({:push, h}, t) do | |
{:noreply, [h | t]} | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Otp.Server do | |
@moduledoc """ | |
A supervisor process that manages multiple child processes. | |
""" | |
use Supervisor | |
alias Otp.Child | |
@start_id 1 | |
@end_id 4 | |
def start_link do | |
Supervisor.start_link(__MODULE__, []) | |
end | |
def init([]) do | |
worker_children = | |
@start_id..@end_id | |
|> Enum.map(fn id -> child_name(id) end) | |
|> Enum.zip([[:hello], [:world], [:blah], [:foo]]) | |
|> Enum.map(fn {name, init} -> worker(Child, [init, [name: name]], id: inspect(name)) end) | |
children = [supervisor(Registry, [:unique, :child_process_registry]) | worker_children] | |
supervise(children, strategy: :one_for_all) | |
end | |
@doc """ | |
Gets the registry name from the child's id. | |
""" | |
def child_name(id), do: {:via, Registry, {:child_process_registry, id}} | |
@doc """ | |
Pops from all of the children processes and returns a list | |
of popped values. | |
""" | |
def pop_from_all do | |
@start_id..@end_id | |
|> Enum.map(fn id -> child_name(id) end) | |
|> Enum.map(fn name -> GenServer.call(name, :pop) end) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment