I need to spawn several independent instances of the same gen_fsm on demand, and then be able to route calls to the correct instance.
Gproc library seems to be a great way of registering processes with arbitrary names. It has a function gproc:reg_or_locate/3 for spawning things on demand without race conditions. This way I don't even need a supervisor - if they crash they'll just get spawned on demand again. But I can't figure out how to apply gproc:reg_or_locate/3
to spawning a gen_fsm or gen_server.
What I've tried so far:
I just call gen_server:start() through that function, it will create an intermediate process, give the name to the intermediate process, the intermediate process will spawn a gen_server and terminate, and I end up with a nameless gen_server.
Both gen_server and gen_fsm export an enter_loop function that seems to do what I need if I feed it to gproc:reg_or_locate/3
, but the documentation reads:
The process must have been started using one of the start functions in proc_lib, see proc_lib(3).
And the docs for gproc:reg_or_locate/3
do not mention that they do anything through proc_lib.
Alternatively I could make the intermediate process acquire the name and then atomically transfer it to the gen_server or gen_fsm that it spawned, but that creates a race condition: the intermediate process would have gen_fsm's name and any messages intended for the gen_fsm would go to the intermediate process and get lost.
I feel like I'm missing something simple here. It's not an uncommon pattern, so there should be a good way to do this. What did I miss?