Clojure 中的线程本地计数器 [英] Threadlocal counter in Clojure

查看:17
本文介绍了Clojure 中的线程本地计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络应用程序,我希望能够跟踪在请求(即线程)中调用给定函数的次数.

I have a web app where i want to be able to track the number of times a given function is called in a request (i.e. thread).

我知道可以使用 ref 以非线程本地方式进行操作,但是我将如何在本地进行线程操作?

I know that it is possible to do in a non-thread local way with a ref, but how would I go about doing it thread locally?

推荐答案

有用 称为 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.

这篇关于Clojure 中的线程本地计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆