[erlang-questions] limiting gen_server

Ulf Wiger ulf.wiger@REDACTED
Sun Aug 9 15:56:00 CEST 2009


These are not calls, though, at least not in the normal
gen_server vernacular. It is not really clear from this
snippet what you are trying to achieve, and what these
messages mean.

In general, it might be better to have a middle-man
process that buffers messages.

Another common form of buffering in gen_servers (at least
one that I commonly use), when the messages to be buffered
are real gen_server calls, is:

handle_call(Req, {Pid,_} = From, S) when ?should_buffer(S) ->
    MRef = erlang:monitor(process, Pid),
    S1 = buffer_req(MRef, {From, Req}, S),
    {noreply, S1};

where the buffer_req() function could store {MRef, {From,Req}}
in a list. The point of doing this is that if the caller
dies, you have a handle_info that handles it:

handle_info({'DOWN', Ref, _, _, _}, S) ->
    Buffered = [{R,Req} || {R, Req} <- S#st.buffered,
                           R =/= Ref],
    {noreply, S#st{buffered = Buffered}};


How you choose to attend to buffered calls is perhaps a
matter of taste. You could order a timer, or keep track
of outstanding calls, along the lines you suggest.

I realise this is not really an answer to your question,
but thought I'd expand the answer a bit. I would go with
a buffering middle-manager in your case, I think.

BR,
Ulf W


Micha wrote:
> Hi,
> 
> I want to restrict the simultanous calls my gen_server handles, since it calls 
> a network service itself and should not flood it :-)
> 
> I do it that way:
> I keep a counter in the state and when the counter reaches the maximum I do 
> the following:
> %% normal handling:
> handle_info({udp, Socket, IPtuple, InPortNo, Packet}, State)
> 		when State#state.cnt < ?LIMIT -> spawn(fun() -> ... end), ...;
> 
> %% max reached:
> handle_info({udp, _Socket, _IPtuple, _InPortNo, _Packet} = Msg, State) ->
>      erlang:send_after(random:uniform(20)+10, self(), Msg),
>     {noreply, State};
> 
> 
> 
> is this o.k. ?
> 
> cheers, 
>  Michael
> 
> 
> 
> ________________________________________________________________
> erlang-questions mailing list. See http://www.erlang.org/faq.html
> erlang-questions (at) erlang.org
> 


-- 
Ulf Wiger
CTO, Erlang Training & Consulting Ltd
http://www.erlang-consulting.com


More information about the erlang-questions mailing list