[root@uxserver bin]# cat counter.erl
-module(counter).
-export([start/0,loop/1,increment/1,value/1,loop/1,stop/1]).
start()->spawn(counter,loop,[0]). %%传递给loop的参数是0
increment(Counter)->Counter!increment.
value(Counter)->Counter!{self(),value},
receive
{Counter,Val}->
Val
end.
stop(Counter)->Counter!stop.
loop(Val)->
receive
increment->
loop(Val+1);
{From, value}->
From!{self(),Val},
loop(Val);
stop->
true;
Other->
loop(Val)
end.
[root@uxserver bin]# erl
Erlang R14B (erts-5.8.1) [source] [smp:4:4] [rq:4]
[async-threads:0] [hipe] [kernel-poll:false]
Eshell V5.8.1 (abort
with ^G)
1> c(counter).
./counter.erl:2: Warning: function loop/1 already exported
./counter.erl:28: Warning: variable 'Other' is unused
{ok,counter}
2> Jsq = counter:start().
<0.39.0>
3> counter:value(Jsq).
0
4> counter:increment(Jsq).
increment
5> counter:increment(Jsq).
increment
6> counter:increment(Jsq).
increment
7> counter:increment(Jsq).
increment
8> counter:value(Jsq).
4
9> counter:increment(Jsq).
increment
10> Jsq!xyzuvw.
xyzuvw
11> counter:value(Jsq).
5
12> counter:stop(Jsq).
stop