[Help] Confused by a code snippet of global module

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

[Help] Confused by a code snippet of global module

Siyang Zhang
Hi
I'm confused by the code snippet of global module. When the 'case clause' matches false, why use spawn_monitor ? Use erlang:monitor could be wrong ? Why ?

Besides, what's the annotation mean ?

Could anybody help me ? Thanks
%% When/if erlang:monitor() returns before trying to connect to the
%% other node this function can be removed.
do_monitor(Pid) ->
case (node(Pid) =:= node()) orelse lists:member(node(Pid), nodes()) of
true ->
%% Assume the node is still up
{Pid, erlang:monitor(process, Pid)};
false ->
F = fun() ->
Ref = erlang:monitor(process, Pid),
receive
{'DOWN', Ref, process, Pid, _Info} ->
exit(normal)
end
end,
erlang:spawn_monitor(F)
end.
Reply | Threaded
Open this post in threaded view
|

Re: [Help] Confused by a code snippet of global module

Karl Velicka
Seems like connecting to a node that is not in the cluster is a blocking operation, and this code is trying to avoid blocking the caller on this connect operation.

On Fri, 20 Mar 2020 at 08:48, Siyang Zhang <[hidden email]> wrote:
Hi
I'm confused by the code snippet of global module. When the 'case clause' matches false, why use spawn_monitor ? Use erlang:monitor could be wrong ? Why ?

Besides, what's the annotation mean ?

Could anybody help me ? Thanks
%% When/if erlang:monitor() returns before trying to connect to the
%% other node this function can be removed.
do_monitor(Pid) ->
case (node(Pid) =:= node()) orelse lists:member(node(Pid), nodes()) of
true ->
%% Assume the node is still up
{Pid, erlang:monitor(process, Pid)};
false ->
F = fun() ->
Ref = erlang:monitor(process, Pid),
receive
{'DOWN', Ref, process, Pid, _Info} ->
exit(normal)
end
end,
erlang:spawn_monitor(F)
end.