Atoms and References

According to the Clojure refs Programming book, it controls consistent, synchronous changes in a shared state, and atoms control uncoordinated synchronous changes in a shared state.

If I understood "coordinated" correctly, it is understood that several changes are encapsulated as a single atomic operation. If so, then it seems to me that coordination requires only a call to dosync.

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)) 
+4
source share
1 answer

Refs coordinated using ... dosync! Dosync and refs work together, dosync is not magical and knows nothing about other reference types or side effects.

Your first example is equivalent:

 (def i (atom 0)) (def j (atom 0)) (do ; <-- (swap! i inc) (swap! j dec)) 
+13
source

Source: https://habr.com/ru/post/1309847/


All Articles