Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save amorphid/f31850eeba4a2f9942fcc872ac756264 to your computer and use it in GitHub Desktop.
Save amorphid/f31850eeba4a2f9942fcc872ac756264 to your computer and use it in GitHub Desktop.
elixir supervised Stack using simple_one_for_one strategy
# iex(80)> {:ok, _} = Test_1.start_child(:foo)
# {:ok, #PID<0.1214.0>}
# iex(81)> Stack.push(:foo, :hello)
# :ok
# iex(82)> Stack.push(:foo, :hello)
# :ok
# iex(83)> Stack.pop(:foo)
# :hello
# iex(84)> Stack.pop(:foo)
# :hello
# iex(85)> Stack.pop(:foo)
defmodule Test_1 do
use Application
import Supervisor.Spec, warn: false
def start(_type, _args) do
children = [
worker(Stack, [])
]
opts = [strategy: :simple_one_for_one, name: Test_1.Supervisor]
Supervisor.start_link(children, opts)
end
def start_child(name) do
Supervisor.start_child(Test_1.Supervisor, [name])
end
end
defmodule Stack do
use GenServer
def start_link(name) do
GenServer.start_link(__MODULE__, [], [name: name])
end
def pop(pid) do
GenServer.call(pid, :pop)
end
def push(pid, value) do
GenServer.cast(pid, {:push, value})
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment