Return to Snippet

Revision: 20641
at November 20, 2009 12:07 by fuzzylollipop


Initial Code
-module(counter).

-export([inc/1,inc/2,dec/1,dec/2,current/1,reset/1,start/1,loop/1]).

start(Name) ->
   register(list_to_atom(Name),spawn(counter,loop,[0])),
   ok.

inc(Name, Amount) ->
    list_to_atom(Name) ! {inc_counter, Amount},
    current(Name).

inc(Name) ->
   inc(Name, 1).

dec(Name, Amount) ->
    list_to_atom(Name) ! {dec_counter, Amount},
    current(list_to_atom(Name)).

dec(Name) ->
   dec(Name, 1).

current(Name) ->
   list_to_atom(Name) ! {get_counter, self()},
   receive
       { counter_value, Count } ->
           Count
   end.

reset(Name) ->
    list_to_atom(Name) ! reset,
    current(Name).

loop(Counter) ->
   receive
       {inc_counter, Amount} ->
           NewCounter = Counter + Amount;
       {dec_counter, Amount} ->
           NewCounter = Counter - Amount;

       {get_counter, Pid} ->
           Pid ! { counter_value, Counter },
           NewCounter = Counter;
       reset ->
           NewCounter = 0
   end,
   loop(NewCounter).

Initial URL
http://www.vertigrated.com/blog/2009/11/counters-in-erlang/

Initial Description


Initial Title
Counters in Erlang

Initial Tags


Initial Language
Other