Question

If I want to always send an event to the initial state of a gen_fsm when I have spawned it, where should I put that function call? Right after start_link or from the process that invoked start_link in the first place. Are there any best practices here?

Was it helpful?

Solution

If you just want to alter the state of the FSM after you start it, you might simply implement the init function for your state machine:

Reading from: http://www.erlang.org/doc/man/gen_fsm.html#Module:init-1

Whenever a gen_fsm is started using gen_fsm:start/3,4 or gen_fsm:start_link/3,4, this function is called by the new process to initialize.

Args is the Args argument provided to the start function.

If initialization is successful, the function should return {ok,StateName,StateData}, {ok,StateName,StateData,Timeout} or {ok,StateName,StateData,hibernate}, where StateName is the initial state name and StateData the initial state data of the gen_fsm.

Also, using the init function, you're sure about the atomicity of the two functions (start_link and init). They will both succeed or fail.

OTHER TIPS

I thik it is right to send first event from the process invoking FSM start function. Or return timeout = 0 from init/1 and handle 'timeout' event in the initial state.

On the other hand, it makes races possible if your gen_fsm is a rgistered process. If that is the case I would send message to the gen_fsm process PID from init/1 befor registering.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top