On Dec 22, 12:25 pm, "Mark Engelberg" <[email protected]>
wrote:
> I misspoke; it's the call to counter that's the problem. Let's say
> you want to use a counter to count the number of times a ref is set,
> something like this:
>
> (dosync (counter) (ref-set r 1))
>
> If your var-set causes the transaction to retry, an atom-based counter
> will increment twice. As I understand it, atoms are one of the most
> "dangerous" things in Clojure, and should be avoided unless you're
> completely sure it will not change the semantics of your program if it
> gets executed multiple times. Aside from the memoization example for
> which it was invented, I am hard-pressed to think of a good use for
> atoms. For something like a counter, you really have to use ref, and
> that should remain people's default when dealing with mutability.
>
> I haven't done much with atoms yet, so if I've misunderstood Rich's
> posts, feel free to explain my mistake.
Thats a valid example. "counter" should not be used
in the dosync.
However, if the counter is meant for a single thread then one
way to use it would be:
... (counter) (dosync (ref-set r 1)) ...
Basically, as counter has side-effects it shouldn't be called
in dosync as stated in the docs ( http://clojure.org/refs )
To quote the docs:
7. I/O and other activities with side-effects should be avoided
in transactions, since transactions will be retried. The io!
macro can be used to prevent the use of an impure function
in a transaction.
End quote.
The above is a general rule so for e.g. we should not
have (dosync (println "done setting") (ref-set r 1)). If my
understanding is correct, this should be:
... (println "done setting") (dosync (ref-set r 1)) ...
If we want a counter to count events across
multiple threads, then yes, it would make sense to
use refs.
If I get it right, atoms are quite useful to maintain state
in the context of a single thread with memoization and
counter (within a thread) being two examples.
There may possibly be performance implications
for refs and atoms but I haven't really benchmarked it.
Parth
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---