DynamicSupervisor.start_child/2 starts a child process on demand under a DynamicSupervisor when the required number of children is unknown in advance. The call sends a synchronous request to the supervisor, which starts the child and serializes concurrent start requests. section 9.2.2
Handle the returned result according to the child’s registration state:
- Match {:ok, pid} when the child starts successfully. section 9.2.3
- Match {:error, {:already_started, pid}} when registration finds an existing process, then reuse that pid. section 9.2.3
- Recognize the efficiency boundary: repeated requests can briefly start and stop redundant children and make the supervisor a bottleneck. section 9.2.3
Listing 9.11 Finding a to-do server (dynamic_workers/lib/todo/cache.ex)
defmodule Todo.Cache do
...
def server_process(todo_list_name) do
case start_child(todo_list_name) do
{:ok, pid} -> pid #1
{:error, {:already_started, pid}} -> pid #2
end
end
defp start_child(todo_list_name) do
DynamicSupervisor.start_child(
__MODULE__,
{Todo.Server, todo_list_name}
)
end
end
Use the Todo.Cache implementation to see successful and already-started results mapped to the process returned to callers. section 9.2.3
