好,我想創建一個櫃檯,使用代碼在這裏二郎 - 爲什麼要創建
-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.
我用我的模塊中的代碼(僅用於測試目的,發現因爲我可以一個新的進程「T弄清楚它爲什麼是這樣做的):
test3() ->
Counter = counter:start().
所以每當我跑TEST3,它會創建一個新的PID一個新的反過程。爲什麼是這樣?我只是想要有一個單一的計數器
但是,當我將一個進程ID分配給計數器時,不應該在下一次爲計數器分配一個不同的PID時引發錯誤?我不認爲這是可能的。我很明顯誤解這裏的東西 我也嘗試過使用寄存器,但後來當我註冊爲某物/任何東西(例如:麪包)它似乎不再起作用。我不能打電話:計數器:增量(麪包)。 ,它只是卡住了。 – user1079404
所以我可以使用,註冊(麪包,計數器:開始()) 然後增加它,使用類似:麪包!增量。在這種情況下 – user1079404