[erlang-questions] Synchronous way to handle timeout between gen_server(s)

Tien Le <>
Tue Oct 22 11:29:55 CEST 2013


Hi,

Please look at my sample code below. I have 2 gen_servers (serv1 and
serv2). serv1 start_link serv2, and traps exit.

%%% serv1:do/0 implementation: %%%
do() ->
    gen_server:call(serv1, do).

handle_call(do, _From, State) ->
    Result = serv2:do(),
    {reply, Result, State}.


%%% serv2:do/0 implementation: %%%
do() ->
    gen_server:call(serv2, do).

handle_call(do, _From, State) ->
    %% Something that takes time like timer:sleep/1
    Result = timer:sleep(5000),
    {reply, Result, State}.


As you can see that serv1's gen_server:call and serv2's gen_server:call
have the same timeout value (5000ms by default).

When I call serv1:do().
serv1 always terminates first due to timed out:

=CRASH REPORT==== 22-Oct-2013::10:26:38 ===
  crasher:
    initial call: serv1:init/1
    pid: <0.43.0>
    registered_name: serv1
    exception exit: {timeout,{gen_server,call,[serv2,do]}}
      in function  gen_server:terminate/6 (gen_server.erl, line 747)
...

One workaround is to increase the timeout of serv1 and serv2
gen_server:call/3, like this:
gen_server:call(serv1, do, *5020*) => gen_server:call(serv2, do, *5010*) =>
timer:sleep(*5000*)

I would like to ask you if there's any nicer and synchronous way to handle
the timeout in this case?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20131022/f78f260a/attachment.html>


More information about the erlang-questions mailing list