tags:

views:

55

answers:

1

According to the book Programming Clojure refs manage coordinated, synchronous changes to shared state and atoms manage uncoordinated, synchronous changes to shared state.

If I understood correctly "coordinated" implies multiple changes are encapsulated as one atomic operation. If that is the case then it seems to me that coordination only requires using a dosync call.

For example what is the difference between:

(def i (atom 0))
(def j (atom 0))

(dosync
  (swap! i inc)
  (swap! j dec))

and:

(def i (ref 0))
(def j (ref 0))

(dosync
  (alter i inc)
  (alter j dec))
+6  A: 

Refs are coordinated using... dosync! Dosync and refs work together, dosync isn't magical and knows nothing of other reference types or side effects.

Your first example is equivalent to:

(def i (atom 0))
(def j (atom 0))

(do ; <--
  (swap! i inc)
  (swap! j dec))
cgrand
Ok, I mistakenly thought that dosync started an atomic code block. Thanks for the answer.
StackedCrooked
It starts a transaction, but doesn't guarantee that everything you put inside it is atomic. The atomic operations are alter and ref-set - these must me called in a transaction. If, for example, you do IO inside a transaction, it may happen more than once.
Zak