[erlang-questions] Singleton Process

Edward Stow <>
Tue Feb 3 10:31:46 CET 2009


Hi,

I have been teaching myself Erlang and had an epiphany regarding the
use of processes to record state without variables (in the imperative
programming sense).

However, I would like to know if this is how you would produce a
counter object that returns an incrementally increasing value.  The
counter needs to be unique across processes. (A singleton process --
is that a correct term in fp / erlang ).

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

next_id() ->
    next_id(start()).

start() ->
    case whereis(counter) of
        undefined ->
            Pid = spawn(fun () -> loop(read_next_id()) end),
            register(counter, Pid),
            Pid;
        Pid ->
            Pid
    end.

next_id(Pid) -> rpc(Pid, next_id).

rpc(Pid, Request) ->
    Pid ! {self(), Request},
    receive
        {Pid, Response} ->
            Response
    end.

loop(Counter) ->
    receive
        {From, next_id} ->
            From ! {self(), Counter},
            save_next_id(Counter + 1),
            loop(Counter + 1)
    end.

read_next_id() ->
    {ok, [Term]} = file:consult("next_id.dat"),
    {next_id, Number} = Term,
    Number.

save_next_id(Number) ->
    {ok, S} = file:open("next_id.dat", write),
    io:format(S, "~p.~n", [{next_id, Number}]),
    file:close(S).


Thanks

-- 

Edward Stow



More information about the erlang-questions mailing list