【发布时间】:2013-12-31 01:01:15
【问题描述】:
我正在尝试使用此处找到的代码创建一个计数器
-module(counter).
-export([start/0,loop/1,increment/1,value/1,stop/1]).
%% First the interface functions.
start() ->
spawn(counter, loop, [0]).
increment(Counter) ->
Counter ! increment.
value(Counter) ->
Counter ! {self(),value},
receive
{Counter,Value} ->
Value
end.
stop(Counter) ->
Counter ! stop.
%% The counter loop.
loop(Val) ->
receive
increment ->
loop(Val + 1);
{From,value} ->
From ! {self(),Val},
loop(Val);
stop -> % No recursive call here
true;
Other -> % All other messages
loop(Val)
end.
我在我的模块中使用的代码是(仅用于测试目的,因为我无法弄清楚它为什么这样做):
test3() ->
Counter = counter:start().
所以每当我运行 test3 时,它都会创建一个带有新 pid 的新计数器进程。为什么是这样?我只是想有一个计数器
【问题讨论】: