且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Clojure 中的线程本地计数器

更新时间:2023-12-03 23:40:16

有用 称为 thread-local.例如,您可以编写 (def counter (thread-local (atom 0))).这将创建一个全局变量,当 deref ed 时,将为每个线程产生一个新的原子.所以你可以用 @@counter 读取当前值,或者用 (swap!@counter inc) 增加它.当然,你也可以用 @counter 来获取原子本身,然后把它当作一个普通的原子.

There's a tool for this in useful called thread-local. You can write, for example, (def counter (thread-local (atom 0))). This will create a global variable which, when derefed, will yield a fresh atom per thread. So you could read the current value with @@counter, or increment it with (swap! @counter inc). Of course, you could also get hold of the atom itself with @counter and just treat it like a normal atom from then on.