开发者

Atoms and references

According to the book Programming Clojure refs manage coordinated, synchronous changes to shared state and atoms man开发者_运维百科age 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))


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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜