Clojure 的 STM 值历史记录可以访问吗?

发布于 2024-11-17 10:10:00 字数 186 浏览 9 评论 0原文

鉴于 STM 保存了 10 个 refs、agents 等值的历史记录,这些值可以读取吗?

原因是,我正在更新大量代理,并且需要保留值的历史记录。如果 STM 已经保留了它们,我宁愿直接使用它们。我在 API 中找不到看起来像是从 STM 历史记录中读取值的函数,所以我猜不是,我也无法在 java 源代码中找到任何方法,但也许我看起来不对。

Given that the STM holds a history of say 10 values of refs, agents etc, can those values be read ?

The reason is, I'm updating a load of agents and I need to keep a history of values. If the STM is keeping them already, I'd rather just use them. I can't find functions in the API that look like they read values from the STM history so I guess not, nor can I find any methods in the java source code, but maybe I didn't look right.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

生寂 2024-11-24 10:10:00

您无法直接访问值的 stm 历史记录。但是您可以使用 add-watch 记录值的历史记录:

(def a-history (ref []))
(def a (agent 0))
(add-watch a :my-history 
  (fn [key ref old new] (alter a-history conj old)))

每次更新a(stm 事务提交)时,旧值都会被转换到 a-history 中保存的序列上。

如果您想访问所有中间值,即使对于回滚事务,您也可以在事务期间将这些值发送给代理:

(def r-history (agent [])
(def r (ref 0))
(dosync (alter r
          (fn [new-val] 
            (send r-history conj new-val) ;; record potential new value 
            (inc r))))                    ;; update ref as you like

事务完成后,代理的所有更改r -history 将被执行。

You cannot access the stm history of values directly. But you can make use of add-watch to record the history of values:

(def a-history (ref []))
(def a (agent 0))
(add-watch a :my-history 
  (fn [key ref old new] (alter a-history conj old)))

Every time a is updated (the stm transaction commits) the old value will be conjed onto the sequence that is held in a-history.

If you want to get access to all the intermediary values, even for rolled back transactions you can send the values to an agent during the transaction:

(def r-history (agent [])
(def r (ref 0))
(dosync (alter r
          (fn [new-val] 
            (send r-history conj new-val) ;; record potential new value 
            (inc r))))                    ;; update ref as you like

After the transaction finished, all changes to the agent r-history will be executed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文