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

6 views
Skip to first unread message

18年梦醒

unread,
Dec 11, 2018, 4:53:52 AM12/11/18
to erlang-q...@erlang.org
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.

```
I run it like this:
```
$ /usr/local/otp_src_21.1.4/bin/erlc a.erl
$ /usr/local/otp_src_21.1.4/bin/erl -s a start -s init stop -noinput
result is true
$ rm a.beam
$ /usr/local/otp_src_20.3.8.15/bin/erlc a.erl
$ /usr/local/otp_src_20.3.8.15/bin/erl -s a start -s init stop -noinput
result is false
```
The same code, in erlang 21, the output is `result is true`, but in erlang 20, the output is `result is false`, that is why the test fail.

I just wonder why the same code but different version, why the result is different?
Is the behaviour changed with the monitor/2 function?

Sverker Eriksson

unread,
Dec 11, 2018, 6:30:04 AM12/11/18
to erlang-q...@erlang.org
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



Reply all
Reply to author
Forward
0 new messages