How to start multiple instances of the same module/function under the Supervisor behavior in erlang? -
having module/function mymodule , how start multiple times under supervisor behavior ?
i need example 2 instances of same process (mymodule) started concurrently. called children identifiers child1 , child2. both point mymodule module want start. have specified 2 different functions to start each instance of worker process "mymodule" ( start_link1 , start_link2 )
-module(my_supervisor). -behaviour(supervisor). -export([start_link/0, init/1]). start_link() -> supervisor:start_link({local, ?module}, ?module, _arg = []). init([]) -> {ok, {{one_for_one, 10, 10}, [{child1, {mymodule, start_link1, []}, permanent, 10000, worker, [mymodule]} , {child2, {mymodule, start_link2, []}, permanent, 10000, worker, [mymodule]} ]}}.
the worker has 2 distinguished start_link functions ( start_link1 , start_link2 ) testing purposes:
-module(mymodule). -behaviour(gen_server). start_link1() -> log_something("at link 1"), gen_server:start_link({global, child1}, ?module, [], []). start_link2() -> log_something("at link 2"), gen_server:start_link({global, child2}, ?module, [], []). init([]) -> ....
with above can see in log message "at link 1" reveal "at link 2" anywhere. not perform in instance of link1 : dies apparently.
the scenario works when name "child1" matches worker module name "mymodule".
as @millebessö asks trying 2 processes have same registered name? mymodule:start_link
register mymodule process under fixed name? if trying start second 1 cause clash. ot trying start multiple my_supervisor
supervisors? name clash. have not included code my_module
.
remember can have 1 process registered under name. holds both local registered processes , registered using global
.
edit: supervisor die well?
a gen_server
, , other behaviours, aren't considered started until init
callback has completed , returned correct value ({ok,state}
). if there error in mymodule:init/1
crash child process before has been initialised , supervisor give up. while supervisor can , restart children when die require start correctly. supervisor:start_link/3
if supervisor , child processes created (i.e. if child process start functions return {ok,child}, {ok,child,info}, or ignore) function returns {ok,pid}, pid pid of supervisor. if there exists process specified supname function returns {error,{already_started,pid}}, pid pid of process.
if module:init/1 returns ignore, function returns ignore , supervisor terminates reason normal. if module:init/1 fails or returns incorrect value, function returns {error,term} term term information error, , supervisor terminates reason term.
i don't know if problem give same behaviour get.
Comments
Post a Comment