Last active
August 12, 2016 06:08
-
-
Save tastywheat/9784b160d1a78d57e0f0 to your computer and use it in GitHub Desktop.
elixir supervised Stack using simple_one_for_one strategy
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
# 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