[erlang-questions] Is the monitor/2 function is much efficient in erlang 21?

Sverker Eriksson sverker@REDACTED
Tue Dec 11 12:26:43 CET 2018


On tis, 2018-12-11 at 17:25 +0800, 18年梦醒 wrote:
> I recently test the sbroker in erlang 21, but the skip_down_match test is
> always failed, I check out the code and make a prototype of the code:
> ```
> -module(a).
> 
> -export([start/0]).
> 
> start() ->
>     Pid = spawn(fun() -> t() end),
>     register(t_name, Pid),
>     spawn(fun() -> t1() end),
>     timer:sleep(1000).
> 
> t1() ->
>     {_, _MRef} = spawn_monitor(fun() ->
>                                        Pid = whereis(t_name),
>                                        Pid ! {pid, self()},
>                                        exit(normal)
>                                end).
> t() ->
>     receive
>         {pid, Pid} ->
>             Ref = monitor(process, Pid),
>             case demonitor(Ref, [flush, info]) of
>                 true ->
>                     io:format("result is true");
>                 false ->
>                     io:format("result is false")
>             end
>     end.
> 
Yes the behavior has changed in 21, but both behaviors are correct and you are
not guaranteed to always get the same behavior in any OTP version.
The program contains a race condition.
At the time demonitor(Ref, [flush,info]) is called you don't know if the
monitored process is still alive or not.
If it's still alive, the monitor will be remove and demonitor returns true.
If it's not alive, no monitor exists (a 'DOWN' message/signal has instead been
sent which will be removed by the 'flush' option) and demonitor will return
false.
/Sverker


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20181211/0b738fa1/attachment.htm>


More information about the erlang-questions mailing list