Supervisor.child_spec/2 derives a child specification from a worker tuple and modifies fields such as :id. This prevents duplicate child identifiers when several instances share one module. section 9.1.5
Assigning unique worker IDs
A database supervisor can build three worker specifications from {Todo.DatabaseWorker, {@db_folder, worker_id}}, then call Supervisor.child_spec(default_worker_spec, id: worker_id). Without the override, autogenerated specifications use Todo.DatabaseWorker as the ID for every worker and supervisor startup fails. section 9.1.5
Listing 9.6 Supervising workers (pool_supervision/lib/todo/database.ex)
defmodule Todo.Database do
@pool_size 3
@db_folder "./persist"
def start_link do
File.mkdir_p!(@db_folder)
children = Enum.map(1..@pool_size, &worker_spec/1)
Supervisor.start_link(children, strategy: :one_for_one)
end
defp worker_spec(worker_id) do
default_worker_spec = {Todo.DatabaseWorker, {@db_folder, worker_id}}
Supervisor.child_spec(default_worker_spec, id: worker_id)
end
...
end
Shows the compact worker-specification function inside a supervisor that starts a pool with a :one_for_one strategy. section 9.1.5
