[erlang-questions] why does rpc:call do this?

Garry Hodgson garry@REDACTED
Wed Jul 13 02:00:34 CEST 2016


I noticed in lib/kernel/src/rpc.erl that got me curious,
as I'm implementing something related. It seems like
there's more work going on than needed, so I suspect
I'm missing some subtlety.

So, rpc:call() is a gen_server call to:

handle_call({call, Mod, Fun, Args, Gleader}, To, S) ->
     handle_call_call(Mod, Fun, Args, Gleader, To, S);

which just invokes:

handle_call_call(Mod, Fun, Args, Gleader, To, S) ->
     RpcServer = self(),
     %% Spawn not to block the rpc server.
     {Caller,_} =
     erlang:spawn_monitor(
       fun () ->
           set_group_leader(Gleader),
           Reply =
               %% in case some sucker rex'es
               %% something that throws
               case catch apply(Mod, Fun, Args) of
               {'EXIT', _} = Exit ->
                   {badrpc, Exit};
               Result ->
                   Result
               end,
           RpcServer ! {self(), {reply, Reply}}
       end),
     {noreply, gb_trees:insert(Caller, To, S)}.

which spawns a process to run the function, stash its results in S, and 
send results as an erlang message to rpc process.

That will then get handled as info message to rpc gen_server, handled here:

handle_info({Caller, {reply, Reply}}, S) ->
     case gb_trees:lookup(Caller, S) of
     {value, To} ->
         receive
         {'DOWN', _, process, Caller, _} ->
             gen_server:reply(To, Reply),
             {noreply, gb_trees:delete(Caller, S)}
         end;
     none ->
         {noreply, S}
     end;

which calls gen_server:reply() to send result to original caller.

So the question is, why do the extra overhead of stashing result in 
gb_tree S and sending it as erlang message,
vs. just having the fun in handle_call_call just use gen_server:reply() 
directly? is it to clean
up the DOWN message from the spawn_monitor? if so, why is the monitor 
part of that needed? What
benefit does it provide?

Any insights appreciated.

Thanks




-- 
Garry Hodgson
Lead Member of Technical Staff
AT&T Chief Security Office (CSO)

"This e-mail and any files transmitted with it are AT&T property, are confidential, and are intended solely for the use of the individual or entity to whom this e-mail is addressed. If you are not one of the named recipient(s) or otherwise have reason to believe that you have received this message in error, please notify the sender and delete this message immediately from your computer. Any other use, retention, dissemination, forwarding, printing, or copying of this e-mail is strictly prohibited."




More information about the erlang-questions mailing list