Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Atoms and references

Tags:

clojure

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))
like image 821
StackedCrooked Avatar asked Dec 13 '22 21:12

StackedCrooked


1 Answers

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))
like image 121
cgrand Avatar answered Jan 25 '23 11:01

cgrand