考虑clojure repl中的以下代码序列
(def elems (atom {}))
(swap! elems assoc 42 [:a 7])
elems
Run Code Online (Sandbox Code Playgroud)
产生预期的{42 [:a 7]}.现在试试
(compare-and-set! elems elems (atom {}))
Run Code Online (Sandbox Code Playgroud)
生产false,意味着compare-and-set!操作没有成功.我很惊讶,因为我希望在操作中elems测试相同.我知道我可以用来完成无条件重置原子的目标,但我想知道为什么不完全相同?elemscompare-and-set!reset!compare-and-set!
compare-and-set! 适用于原子引用的值,而不是原子本身.
clojure.core/compare-and-set!
([atom oldval newval])
Atomically sets the value of atom to newval if and only if the
current value of the atom is identical to oldval. Returns true if
set happened, else false
Run Code Online (Sandbox Code Playgroud)
你可能想要这个:
(compare-and-set! elems @elems {})
Run Code Online (Sandbox Code Playgroud)