gen_server partial replies
Chandrashekhar Mullaparthi
Chandrashekhar.Mullaparthi@REDACTED
Sat Nov 22 23:48:18 CET 2003
> -----Original Message-----
> From: Mikael Karlsson [mailto:mikael.karlsson@REDACTED]
> Sent: 22 November 2003 14:00
> To: Bengt Kleberg; - Erlang Questions
> Subject: Re: gen_server partial replies
>
> One thing in the gen_server code bothers me a bit though.
> There is the main
> loop function which calls the handle_msg function which calls
> the loop
> function and so on. Is this OK for an infinite process? Will
> the compiler
> handle the stack properly?
>
> loop(Parent, Name, State, Mod, Time, Debug) -> ...
> handle_msg(Msg, Parent, Name, State, Mod, Time);
>
> handle_msg({'$gen_call', From, Msg}, Parent, Name, State,
> Mod, _Time) ->
> case catch Mod:handle_call(Msg, From, State) of
> {reply, Reply, NState} ->
> reply(From, Reply),
> loop(Parent, Name, NState, Mod, infinity, []);
> ...
The handle_msg and loop function are tail-recursive functions, so they wont
cause the stack to grow. The compiler ensures that tail-recursive functions
operate in constant stack space.
Here is an example of a function which is not tail-recursive. The function
adds all the numbers in a list. Here you can see that each element of the
list is being saved on the stack and the addition takes place when all the
elements have been saved on the stack and it unwinds. The larger the list,
the larger the stack will be.
add([H | T]) ->
H + add(T);
add([]) ->
0.
The same function can be written in a tail-recursive manner as follows. Here
an extra variable is used to store the result of the addition each time and
nothing is saved on the stack.
add(List) ->
add(List, 0).
add([H | T], Acc) ->
add(T, H + Acc);
add([], Acc) ->
Acc.
cheers
Chandru
NOTICE AND DISCLAIMER:
This email (including attachments) is confidential. If you have received
this email in error please notify the sender immediately and delete this
email from your system without copying or disseminating it or placing any
reliance upon its contents. We cannot accept liability for any breaches of
confidence arising through use of email. Any opinions expressed in this
email (including attachments) are those of the author and do not necessarily
reflect our opinions. We will not accept responsibility for any commitments
made by our employees outside the scope of our business. We do not warrant
the accuracy or completeness of such information.
More information about the erlang-questions
mailing list