[erlang-questions] Re: Supervisors as factories *and* registries

Garrett Smith g@REDACTED
Tue Mar 23 00:40:18 CET 2010


On Mon, Mar 22, 2010 at 1:31 PM, Jay Nelson <jay@REDACTED> wrote:
> Garrett Smith while using supervisors wrote:
>
>> I wish ... I could maintain an index (for example) that would let me
>> access children more efficiently.
>
> This is not a very "functional" (as in functional language) approach, but it
> should do the trick in the way supervisors are intended to be used.  It
> relies on ets for the stateful (i.e., non-functional) aspect but the locally
> known name of the ets table affords you to treat it as if it were stored in
> the state argument (which doesn't exist in the case of supervisors).

Up to this point, I've been leery of using ETS tables (feels like
cheating, like using the process registry), but given the closed
nature of supervisor, I suppose it's a good option to keep this logic
contained in a single module. (I'm also conveniently overlooking the
fact that core Erlang, like timer, uses ETS extensively, still.)

> Whenever you start a child, it calls apply(M, F, A) which is identified in
> your init function for each childspec.
>
> In the start_link of the supervisor create a named ets table.
>
> Write a function that is local to your supervisor (this is conceptual, you
> need to play with return values, errors, restart vs start, and so on):
>
> launch_child(SupRef, Childspec, ChildKey) ->
>    case supervisor:start_child(Childspec) of
>        {ok, Pid} =
>          ets:insert(?ETS_NAME, {ChildKey, Pid, Childspec}),
>         {ok, Pid};
>       ... other cases ...
>    end.
>
>
> Now you can globally access the ets table to lookup a Childspec or Pid using
> your own key.  Supervisor is no more complicated and works as is.  You need
> to make sure your launch_child function doesn't crash the supervisor, so try
> to make it as simple as possible to do what you need.

Okay, gonna give this a try. Thanks!

Garrett


More information about the erlang-questions mailing list