在clojure同步计数器

时间:2011-09-18 12:47:45

标签: multithreading clojure volatile

如果我想保留一个全局计数器(例如,计算跨多个线程的传入请求数),那么在java中执行的最佳方法是使用volatile int。假设,正在使用clojure是否有更好的(更好的吞吐量)方法呢?

2 个答案:

答案 0 :(得分:13)

我会在Clojure中使用atom执行此操作:

(def counter (atom 0N))

;; increment the counter
(swap! counter inc)

;; read the counter
@counter
=> 1

这完全是线程安全的,并且性能出奇的高。此外,由于它使用了Clojure的abitrary-precision数字处理,因此它不易受整数溢出的影响,因为volatile可以是......

答案 1 :(得分:7)

将全局计数器定义为agent

(def counter (agent 0))

要将代理中包含的值send增加到代理的函数(在本例中为inc):

(send counter inc)

要阅读当前值,您可以使用deref@阅读器宏:

@counter ;; same as (deref counter)

代理只是几种可用引用类型中的一种。您可以在Clojure网站上阅读有关这些内容的更多信息: