[erlang-questions] gen_fsm and active sockets (Dave Smith)

Ingela Anderton Andin ingela@REDACTED
Thu Jan 17 09:58:34 CET 2008


> I'm using gen_fsm to manage a socket connection, and have a question
> about how one SHOULD use gen_fsm for this purpose. I'm specifically
> using the "active" mode for the socket, so I'm currently receiving
> events via the handle_info/3 callback.

You probably want to use active once instead so that you get flow control.
 
> I understand why the socket
> events arrive there, but I wonder what the best way to pass the event
> along to the actual FSM is. I see there being 3 possible options:

The most logical way would be to send an event message to yourself by calling
the gen_fsm:send_event/2.

> 1. Receive socket events on a dedicated process and pass events into
> gen_fsm via that process. 

I can not see any real gain in doing that. It only creates parallelism
where there is non and that makes your program more complex and
opens up for crating race-conditions and other problems that 
really should not be there.

> Upside is that this provides nice separation
> of socket and fsm logic.

You already have that separation in that you handle the socket
in handle_info and the events in the state functions.

> Downside there is that I'm doubling the
> number of processes -- i.e. i had one process per socket, now I have
> two. 

Erlang processes are very light weight but you should only create new
processes when you need them. A server will often spawn 
a new process to handle each request. Each participant in a telephone call
can be represented by a process.
A good principle when deciding which processes you need is to
have one process for each truly parallel activity in the
system.

> 2. Receive socket events in handle_info and invoke
> gen_fsm:send_event() from there. This seems like the "obvious"
> approach, 

Yes like I said earlier this is the logic thing to do.

> but it feels wrong -- I'm already in process and don't
> really want to queue up another event. Again, possibly a "hangover"
> from non-Erlang land.

I would not worry about that, I doubt that the overhead of sending
a message to yourself is significant. (And yes there is a little
overhead in the gen_fsm code also)  

> 3. Receive socket events in handle_info, then do a
> ?MODULE:StateName({socket_event ...}, State). Avoids (perceived)
> verhead of approach #3, but...is this a good idea?!

This could be a way to optimize if profiling activities conclude  that
that gen_fsm is a big bottleneck, but from a best practice and easy
to maintain view I would rather not do this.

Regards Ingela - OTP team








More information about the erlang-questions mailing list