Supervisors as factories *and* registries

Jay Nelson jay@REDACTED
Mon Mar 22 19:31:49 CET 2010


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).

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.

jay



More information about the erlang-questions mailing list