[erlang-questions] How to do counters?
Witold Baryluk
baryluk@REDACTED
Mon Jun 29 18:24:34 CEST 2009
Dnia 2009-06-29, pon o godzinie 12:09 -0400, Jarrod Roberson pisze:
> first off thanks for all the examples, it is very nice to see that everyone
> suggested pretty much the same solution.
> I have joe's book and ordered the new "erlang programming" book from amazon
> yesterday.
> ok, I think I have gotten my head around how a process can store state, and
> using messages to manipulate it.
> I understand how to manipulate the counter examples that were provided.
>
> One thing I can't figure out now is how to make many counters.
> One example usings ?MODULE to register the process, another uses
> "global_counter" as name.
> Either way the only way I see to create multiple unique counters is to
> copy/paste the module and rename/edit it.
> That doesn't "smell" right to me. Is there a better way to create
> "instances" of these counter module examples?
You need to uniqly idendify counter. You can handle all counter in
single process and add additional information to the message, about
which counter should be incremented.
Another way is using just presented examples, and registering them on
different names, or not registering them at all (they will be only
referenced by Pid returned from spawn).
You can register it using something like that:
start(X) ->
Pid = spawn(counter,loop,[0]),
Name = list_to_atom("counter_"++X),
register(Name, Pid),
ok.
--
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/20090629/bf202477/attachment.bin>
More information about the erlang-questions
mailing list