[erlang-questions] How to do counters?

Witold Baryluk <>
Tue Jun 30 01:56:55 CEST 2009


Dnia 2009-06-30, wto o godzinie 11:46 +1200, Richard O'Keefe pisze:
> On Jun 30, 2009, at 4:09 AM, Jarrod Roberson wrote:
> > That doesn't "smell" right to me. Is there a better way to create
> > "instances" of these counter module examples?
> 
> Just have a counter:new() function that returns you the PID
> of a new process.
> 
> 	-module(counter).
> 	-export([new/0, read/1, up/1, down/1, reset/1]).
> 
> 	new() ->
> 	    {counter,spawn(fun () -> loop(0) end)}.
> 
> 	loop(N) ->
> 	    receive {Msg,Sender} ->
> 	        Sender ! {self(), N},
> 	        loop(case Msg
> 		       of read -> N
> 		        ; up   -> N + 1
> 		        ; down -> N - 1
> 		        ; reset-> 0
> 		     end)
> 	    end.
> 
> 	read(Counter) ->
> 	    ipc(Counter, read).
> 
> 	up(Counter) ->
> 	    ipc(Counter, up).
> 
> 	down(Counter) ->
> 	    ipc(Counter, down).
> 
> 	reset(Counter) ->
> 	    ipc(Counter, reset).
> 
> 	ipc({counter,Pid}, Msg) when is_pid(Pid) ->
> 	    Pid ! {Msg,self()},
> 	    receive {Pid,Result} -> Result end.
> 
> Bind the result of a call to counter:new() to a variable,
> and use that variable.  Example:
> 
> 1> c(counter).
> {ok,counter}
> 2> C1 = counter:new().
> {counter,<0.38.0>}
> 3> C2 = counter:new().
> {counter,<0.40.0>}
> 4> counter:up(C1).
> 0
> 5> counter:read(C1).
> 1
> 6> counter:read(C2).
> 0
You can also use parametrized modules:


-module(counter).
-export([new/0]).

new() ->
	C = {counter,spawn(fun () -> loop(0) end)},
	counter2:instance(Counter).

loop(X) -> ...


-module(counter, [Counter]). %% parametrized module
-export([read/0, up/0, down/0, reset/0]).

read() ->
    ipc(Counter, read).

...




Then just use:

C1 = counter:new().
C2 = counter:new().
C1:up().
C1:read().
C2:read().


This is just syntactic sugar.


-- 
Witold Baryluk
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 197 bytes
Desc: To jest cz??? wiadomo?ci podpisana cyfrowo
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090630/6d226a10/attachment.bin>


More information about the erlang-questions mailing list