Permalink
Browse files

monitor client

  • Loading branch information...
davidsulc committed Jun 25, 2018
1 parent 412b87c commit 7ab91215798ee6bc218be362d01ccfa98f3789ee
Showing with 18 additions and 3 deletions.
  1. +18 −3 lib/pool_toy/pool_man.ex
View
@@ -2,7 +2,7 @@ defmodule PoolToy.PoolMan do
use GenServer
defmodule State do
defstruct [:size, workers: []]
defstruct [:size, workers: [], monitors: %{}]
end
@name __MODULE__
@@ -28,8 +28,11 @@ defmodule PoolToy.PoolMan do
{:reply, :full, state}
end
def handle_call(:checkout, _from, %State{workers: [worker | rest]} = state) do
{:reply, worker, %{state | workers: rest}}
def handle_call(:checkout, {from, _}, %State{workers: [worker | rest]} = state) do
%State{monitors: monitors} = state
ref = Process.monitor(from)
monitors = Map.put(monitors, ref, worker)
{:reply, worker, %{state | workers: rest, monitors: monitors}}
end
def handle_cast({:checkin, worker}, %State{workers: workers} = state) do
@@ -46,6 +49,18 @@ defmodule PoolToy.PoolMan do
{:noreply, %{state | workers: workers}}
end
def handle_info({:DOWN, ref, :process, _, _}, %State{workers: workers, monitors: monitors} = state) do
workers =
case Map.get(monitors, ref) do
nil -> workers
worker -> [worker | workers]
end
monitors = Map.delete(monitors, ref)
{:noreply, %{state | workers: workers, monitors: monitors}}
end
def handle_info(msg, state) do
IO.puts("Received unexpected message: #{inspect(msg)}")
{:noreply, state}

0 comments on commit 7ab9121

Please sign in to comment.