lecture 05

This commit is contained in:
SowinskiBraeden committed 2026-10-08 20:59:37 -07:00
1 parent 14dc7cdbac
commit 06c4362a87
19 files changed
+439

No files matched your search

@@ -0,0 +1,26 @@
defmodule Counter.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
@registry Counter.Registry
@table Counter.Table
use Application
@impl true
def start(_type, _args) do
children = [
{Registry, name: @registry, keys: :unique}, # recall same as {Registry, [name: @registry, keys: :unique]}
# Starts a worker by calling: Counter.Worker.start_link(arg)
# {DynamicSupervisor, name: Counter.DynamicSupervisor, strategy: :one_for_one}
{PartitionSupervisor, name: Counter.DynamicSupervisors, child_spec: Counter.DynamicSupervisor}
]
:ets.new(@table, [:named_table, :public])
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Counter.Supervisor]
Supervisor.start_link(children, opts)
end
end
@@ -0,0 +1,18 @@
defmodule Counter.DynamicSupervisor do
use DynamicSupervisor
def start_link(_) do
DynamicSupervisor.start_link(__MODULE__, nil)
end
def start_worker(name) do
DynamicSupervisor.start_child(
{:via, PartitionSupervisor, {Counter.DynamicSupervisors, self()}},
{Counter.Worker, name})
end
@impl true
def init(_) do
DynamicSupervisor.init(strategy: :one_for_one)
end
end
@@ -0,0 +1,52 @@
defmodule Counter.Worker do
use GenServer
@registry Counter.Registry
@table Counter.Table
### Client API ###
def start_link(name) do
GenServer.start_link(__MODULE__, name, name: via(name))
end
def value(name) do
GenServer.call(via(name), :value)
end
def inc(name, amt \\ 1) do
GenServer.cast(via(name), {:inc, amt})
end
# wrap the name in a triple to use the Registry to get the
# process ID by name
defp via(name) do
{:via, Registry, {@registry, {__MODULE__, name}}}
end
### Server Impl ###
@impl true
def init(arg) do
name = {__MODULE__, arg}
value = case :ets.lookup(@table, name) do
[] -> 0
[{_, v}] -> v
end
{:ok, {name, value}}
end
@impl true
def handle_call(:value, _from, {_, value} = state) do
{:reply, value, state}
end
@impl true
def handle_cast({:inc, amt}, {name, value}) do
{:noreply, {name, value + amt}}
end
# save state to term table when process terminates
@impl true
def terminate(_, state) do
:ets.insert(@table, state)
end
end