【发布时间】:2014-11-10 06:56:46
【问题描述】:
大多数原子运算符返回交换之前的前一个值,例如 C++ 中的std::atomic::fetch_add。使用 atomic int 作为从 0 开始的全局递增 id 是很自然的。为什么 Clojure 的 atom 返回被交换的值?
(def global-counter (atom 0))
(defn next! [] (dec (swap! global-counter inc)))
有没有更好的方法在 Clojure 中创建从零开始的计数器?
【问题讨论】:
-
(def global-counter (atom -1))并摆脱dec电话? -
@hsestupin 它不适用于 java 中不存在的 unsigned int :)
-
好的,请看下面我的回答。 AtomicInteger 比 clojure atom 更快,看起来更惯用,更适合您的情况。
-
谢谢!我还想了解在 Clojure 中返回先前值的决定背后的原因。
标签: clojure