Last active
March 24, 2020 19:38
-
-
Save alexandreservian/74b3994509870588f5d6437467f3a29b to your computer and use it in GitHub Desktop.
Stack usando spawn
This file contains 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 ProcessInElixir.StackNormal do | |
def start_link(initialStack \\ []) do | |
pid = spawn_link __MODULE__, :loop, [initialStack] | |
{:ok, pid} | |
end | |
def child_spec(opts) do | |
%{ | |
id: __MODULE__, | |
start: {__MODULE__, :start_link, [opts]}, | |
type: :worker, | |
restart: :permanent, | |
shutdown: 500 | |
} | |
end | |
def loop(stack \\ []) do | |
receive do | |
{:push, value} -> | |
newStack = [value | stack] | |
loop newStack | |
{:pop, sender} -> | |
[head | tail] = stack | |
send sender, {:ok, head} | |
loop tail | |
{:show, sender} -> | |
send sender, {:ok, Enum.reverse stack} | |
{:raise} -> | |
raise "error no processo" | |
end | |
loop stack | |
end | |
def push(pid, value), do: send pid, {:push, value} | |
def raiseProcess(pid), do: send pid, {:raise} | |
def pop(pid) do | |
send pid, {:pop, self()} | |
receive do {:ok, itemDeleted} -> itemDeleted end | |
end | |
def show(pid) do | |
send pid, {:show, self()} | |
receive do {:ok, stack} -> stack end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment