tags:

views:

98

answers:

3

Tutorials are abound for working with gen_servers that are named in an OTP application. However, I've been unable to find a good example of dynamically spawning servers that are not registered (not named). Can someone point to a good, simple example? Not ejabberd, for example, where there is a lot to confuse the core idea I'm trying to get at.

Thanks.

A: 

I have some dynamic spawning of workers in a supervision tree going on in http://github.com/noss/iserve. The iserve application has a master registered process that i call iserve_master it is supervised together with a simple one for one mode supervisor.

The iserve_master is for asking iserve to start a http server. It can have multiple iservers, as long as they bind to unique addresses. The started servers construct a name for themself though, but that is to simplify debugging, it generates an atom using the port name.

A server is is an "eternal" loop waiting for a iserve_socket to call back about having accepted a connection. It starts the first one in init.

The started socket is not under supervision because it is not able to restart without losing the http socket connection anyway. And I see it as a bit of a feature to not care. Fire and forget.

Its far from perfect, but an architecture that I somewhat like.

Christian
A: 

The rabbitmq-shovel plugin appears to have an example of this - see rabbit_shovel_sup.erl and rabbit_shovel_worker.erl. It spawns worker gen_server processes based on settings in a configuration file.

Greg Campbell
+1  A: 

the simplest example would be:
leave out the first argument {local,name} in *gen_server:start*: i.e. assuming your module is called mod:

start(ArgX) ->
    gen_server:start(mod, [ArgX], []).

then you do:

> {ok, Pid} = gen_server:start(mod, [66], []).

and the gen_server is up and running.
each call to this function spawns a new unnamed gen_server process. note that this example is using start (and not start_link) for stand-alone use (outside of a supervisor context).

kr1