Reputation: 55
From an old exam, there is a question I don't understand the answer to. The module for the question looks like this:
-module(p4).
-export([start/0, init/0, f1/1, f2/1, f3/2]).
start() ->
spawn(fun() -> init() end).
init() -> loop(0).
loop(N) ->
receive
{f1, Pid} ->
Pid ! {f1r, self(), N},
loop(N);
{f2, Pid} ->
Pid ! {f2r, self()},
loop(N+1);
{f3, Pid, M} ->
Pid ! {f3r, self()},
loop(M)
end.
f1(Serv) ->
Serv ! {f1, self()},
receive {f1r, Serv, N} -> N end.
f2(Serv) ->
Serv ! {f2, self()},
receive {f2r, Serv} -> ok end.
f3(Serv, N) ->
Serv ! {f3, self(), N},
receive {f3r, Serv} -> ok end.
The question asks to consider the following function as part of the code, and what the result of the function would be. The correct answer is 2. I would think it'd be 3, since the "increase-call" f2(Server)
is after the response of self()!{f1r, Server, 2}
.
test3() ->
Server = start(),
self()!{f1r, Server, 2},
f2(Server),
f1(Server).
My questions are:
self()!{f1r, Server, 2}
work? self()!{f1r, Server, 2}
a response from the receive clause in the loop(N)
of the f1(Serv)
function?Upvotes: 0
Views: 89
Reputation: 1189
self()!{f1r, Server, 2}
sends the {f1r, Server, 2}
to itself.
This message will wait in the inbox until received.
Then f2
gets executed and then f1
.
It is in this last function, when the last line receive {f1r, Serv, N} -> N end
is executed, the process running test3
receives the message waiting in the inbox (the one sent to itself) and returns the 2 in that message.
Note that at the end of the program, there would have been a {f1r, <process number>, N}
waiting in the inbox, N having a value of 1.
Upvotes: 1