[erlang-questions] Sending messages to gen_event manager

Adam Kelly <>
Sat Jul 21 16:45:09 CEST 2007


On 7/21/07, Ben Hood <> wrote:
> 1. As a alternative to the notify/2 call, if if store the Pid of the
> event manager when it is started, i.e.
>
> {ok, Pid } = gen_event:start_link( {local, man} ).
>
> can I just implement a handle_info/2 callback on my handler and then I
> can send it events as such:
>
> Pid ! { my_message }

You can choose to use names and events with either method.   All of
these are equivalent:

Pid ! {notify, Event}.
man ! {notify, Event}.
gen_event:notify( Pid, Event ).
gen_event:notify( man, Event ).

I'd advise you  to use gen_event:notify, as it hides the
implementation details of the event manager.  If something is an
event, it's also clearer to use handle_event rather than handle_info.

> Are these approaches equivalent apart from the fact that one is a
> by-name invocation and the other is a by-pid invocation?
>
> Does the by-pid invocation have any implications on the state,
> lifecycle or supervision tree of the handler?

The Pid approach doesn't really work once you place the event manager
in a supervision tree.  When the event manager dies it will be
respawned using a different Pid, and you'll have to rediscover the
Pid,  Using a name avoids this problem.  On the other hand if you wish
to have multiple instances of the event manager, you might be better
off using the Pid.  (I'm not sure why you might do this, but you never
know...)

> 2. Say I have multiple event handlers that need to respond differently
> to different types of events, it is a sounder design to add multiple
> callbacks to one event manager and then pattern match on the
> handle_event/2 callback, or does it make more sense to just create a
> new event manager for each event type?
>
> Naively I would go for the latter option, but this may create lots of
> event manager processes. Is this problematic?

This is pretty much a design decision depending on the types of
events, and what you do with them.  Either approach will work fine,
it's just a matter of figuring out which is simplest in your case.

Be aware that all event handlers run in series in the process of the
event manager.  An event handler which crashes is silently deleted
from the event manager - use add_sup_handler to get notifications of
this.

Adam.



More information about the erlang-questions mailing list