the-little-elixir-otp-guidebook-code icon indicating copy to clipboard operation
the-little-elixir-otp-guidebook-code copied to clipboard

terminating children in thy_supervisor.ex

Open gabrielgrover opened this issue 8 years ago • 1 comments

I am reading through the book and I am confused on pages 102 - 103. for the following handle_call cb we delete the child from the state (HashDict).

def handle_call({ :terminate, pid }, _from, state) do case terminate_child(pid) do :ok -> new_state = state |> HashDict.delete(pid) { :reply, :ok, new_state } :error -> { :reply, { :error, "error terminating child" }, state } end end

defp terminate_child(pid) do Process.exit(pid, :kill) :ok end

Benjamin then goes to explain that we must provide the following handle info cb to terminate the child process, since we used Process.exit(pid, :kill)

def handle_info({ :EXIT, from, :killed }, state) do new_state = state |> HashDict.delete(from) { :noreply, new_state } end

To me it seems you are deleting the child process twice since the following line

new_state = state |> HashDict.delete(from)

is in both the handle_call and handle_info callbacks. What is going on here?

gabrielgrover avatar Feb 08 '17 17:02 gabrielgrover

Yep, I came across the same problem when going through the code in the book. This isn't actually a problem because both HashDict.delete and the newer Map.delete simply return the same map if the key cannot be found. That being said, I agree with this issue that the code is confusing and repetitive. I posted an expanded post on the topic similar to this issue on the official book forum here.

jswny avatar Apr 12 '17 17:04 jswny