when to use Gen_Fsm and when to use Gen_Server?
Asked Answered
S

1

10

After checking out Gen_Fsm and Gen_Server documents, I found that, more or less, they act as similar behavior. In my opinion, if there is one loop function for sending broadcast or listening tcp sock, it is better to use Gen_Fsm, or else to use gen_server. i want to know whether it is right ?

Saritasarkaria answered 1/6, 2011 at 12:34 Comment(0)
C
9

You have seen right that gen_server and gen_fsm are very similar in functionality.

However in most programs there is much more gen_server than gen_fsm usage.

In my opinion gen_fsm is only useful when the usage 100% fits the gen_fsm model. So there has to be a simple and clear finite state machine that fits to your problem. Be aware that usually FSM's state count tends to explode in the face of the real world.

If you find yourself having lots of secondary state information in gen_fsm's Statevariable its probably time to switch to gen_server and add gen_fsm' s state to the State variable.

Generally when in doubt: use gen_server

One disadvantage of both gen_server and gen_fsm (which comes out worse in gen_fsmusually) is that you can't use selective receive. Selective receive is a important tool for reducing state machine complexity in real world applications.

To have the advantage of both selective receive and OTP behaviours I'd recommend plain_fsm.

Compare answered 1/6, 2011 at 16:24 Comment(2)
you said: "... you can't use selective receive.", why is that? I think as long as we don't touch those messages we are not interested in, like $gen_blah_blah and system messages, we are fine. If we can control the incoming message's format, we can only receive those we are interested in, like this receive {some_app_specific_message_tag, Msg} -> ...Kneehigh
@NotanID well you will have to implement selective receive yourself in handle_info, and won't be able to use gen_server:call|cast. At this point, plain_fsm is a better choice.Harlotry

© 2022 - 2024 — McMap. All rights reserved.