Skip to content

Instantly share code, notes, and snippets.

@amorphid
Last active March 25, 2016 17:50
Show Gist options
  • Save amorphid/ec6e6f80493bb9a408d5 to your computer and use it in GitHub Desktop.
Save amorphid/ec6e6f80493bb9a408d5 to your computer and use it in GitHub Desktop.
Elixir counter
defmodule Counter do
use GenServer
# Client
def decrement(pid) do
GenServer.call(pid, :decrement)
end
def count(pid) when is_pid(pid) do
GenServer.call(pid, :count)
|> elem(1)
end
def increment(pid) do
GenServer.call(pid, :increment)
end
def start_link do
start_link(0)
end
def start_link(integer, opts \\ []) when is_integer(integer) do
GenServer.start_link(__MODULE__, integer, opts)
end
# Server
def handle_call(:count, _from, state) do
{:reply, state, state}
end
def handle_call(:difference, _from, state) do
difference = state - 1
{:reply, difference, difference}
end
def handle_call(:increment, _from, state) do
sum = state + 1
{:reply, sum, sum}
end
end
import Supervisor.Spec
children = [
worker(Counter, [])
]
{:ok, sup_pid} = Supervisor.start_link(children, strategy: :simple_one_for_one)
{:ok, pid } = Supervisor.start_child(sup_pid, [10])
IO.puts Counter.increment pid # 11
IO.puts Counter.increment pid # 12
IO.puts Counter.increment pid # 13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment