我已经开始学习Erlang了,我已经开始使用邮箱和服务器,我的代码遇到了一个我不理解的错误
start()->
Counter = spawn(fun counter/0),
client(Counter).
counter(N) ->
receive
{get_state, P} -> P!N;
{inc_state} -> N+1
end.
client(P) ->
N!get_state,
timer:sleep(100 + rand:uniform(900)),
N!inc_state,
timer:sleep(100 + rand:uniform(900)),
done.
我在N上得到未绑定的错误而在P.上未使用
答案 0 :(得分:0)
-module(counter).
-compile([export_all]).
start()->
Counter = spawn(fun counter/0),
client(Counter).
% you have started your counter without parameter, (this is the meaning of
% counter/0) this intermediate function call the counter with the init value 0.
counter() -> counter(0).
counter(10) ->
io:format("counter has reach 10, it stops~n");
counter(N) ->
NewCount = receive
{get_state, P} ->
% send the answer
P ! N,
% and keep the state unchanged
N;
{inc_state} ->
N+1
end,
% never forget to do a recursive loop if you want that your process keep alive!
counter(NewCount).
client(stop) ->
io:format("client has not receive any answer, it stops~n");
client(P) ->
% the pid of your server is P, and you have to respect your message definition,
% what is expected by the server
% in your code you are using N instead, which is undefined (unbound),
% and you don't use P: this is the reason of the error and warning messages.
P ! {get_state,self()},
timer:sleep(100 + rand:uniform(900)),
% add this to show that the state is incrementing
Continue = receive
State ->
io:format("state is ~p~n",[State]),
P
after 1000 ->
stop
end,
P ! {inc_state},
timer:sleep(100 + rand:uniform(900)),
% recursive loop otherwise it will stop at the first step, leaving a counter process alive.
% my proposal to stop these processes.
client(Continue).