Skip to content

Instantly share code, notes, and snippets.

@cybrox
Last active April 30, 2019 11:13
Show Gist options
  • Save cybrox/33d6062b8068b617c174be0760ffd008 to your computer and use it in GitHub Desktop.
Save cybrox/33d6062b8068b617c174be0760ffd008 to your computer and use it in GitHub Desktop.
ex-mag6.ex
defmodule Pragmatic do
def supervisor(worker) do
spawn_link(fn ->
worker_pid = spawn_link(worker)
Process.register(worker_pid, :worker) # <- I added this so we can find our worker
Process.flag(:trap_exit, true)
receive do
{:EXIT, ^worker_pid, _} ->
supervisor(worker)
end
end)
end
def worker(state \\ %{}) do
receive do
{:set, value} ->
worker(value)
{:get, from} ->
send(from, state)
worker(state)
end
end
end
pseudo_agent = fn -> Pragmatic.worker() end
pseudo_supervisor = Pragmatic.supervisor(pseudo_agent)
agent_pid = Process.whereis(:worker)
# Our very simple implementation does not wait until the worker process
# is actually started, so if we use this outside iex, this is a race condition!
send(worker_pid, {:set, 1})
send(worker_pid, {:get, self()})
receive do
any -> IO.inspect any
end
#> 1
send(worker_pid, {:set, 3})
send(worker_pid, {:get, self()})
receive do
any -> IO.inspect any
end
#> 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment