concurrency - 在下面的 Clojure 代码中,alter 可以替换为 Commute 吗?

标签 concurrency clojure

(def alice-height
  (ref 3))

(def right-hand-bites
  (ref 10))

(defn eat-from-right-hand []
  (dosync
    (when (pos? @right-hand-bites)
      (alter right-hand-bites dec)
      (alter alice-height #(+ % 24)))))

此代码来自 Living Clojure 一书。书中,作者还以为例进行了说明。更改 替换为 通勤 .我想知道 pos?一开始的测试,真的可以做这个替换吗?

最佳答案

不,更换 altercommute递减时right-hand-bites是不正确的。

有条件的意图显然是为了防止right-hand-bites从变得消极。递减仅在 right-hand-bites 的假设下有效直到交易结束才会改变。同时,喜欢 alter , commute有自己的 ref 世界快照 View ,它将在提交时重新读取并重新应用通勤函数到 ref,这将是该程序中的一个错误。

所以,与 commute可以将负值提交给 right-hand-bites .

要么坚持 alter ,或使用 ensure 而不是 @ (尽管这使得整个通勤练习变得毫无意义)。

关于concurrency - 在下面的 Clojure 代码中,alter 可以替换为 Commute 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955386/

相关文章:

concurrency - 分布式系统上的邮箱处理器

go - 一段时间后停止协程

Python 线程池——创建子任务并等待它们的任务

clojure - Clojure 列表中的惯用和懒惰最终为真

vector - Clojure:使用索引为向量中的每个元素调用一个函数

database - 并发数据库事务

concurrency - Agent之间如何通信?

java - Clojure - "Exception in thread "main“java.lang.ClassCastException : seesaw. core.proxy”

recursion - Clojure 中的重组映射。将当前map中对应的值放入新map中

file - 大型 clojure 项目是如何组织的?