【发布时间】:2017-03-02 20:39:03
【问题描述】:
我是 clojure 的新手,我正在尝试实现经典的并发示例,即 bank account transfer。我想使用transactional memory 来实现它。
这是java中的一个例子
static class Account {
private double balance;
public synchronized void withdraw(double value) {
balance -= value;
}
public synchronized void deposit(double value) {
balance += value;
}
}
static synchronized void transfer(Account from, Account to, double amount) {
from.withdraw(amount);
to.deposit(amount);
}
在我的实现中不确定,但它似乎有效。
这是我在clojure中的代码
(deftype Account [balance])
(def account1 (Account. (ref 100)))
(def account2 (Account. (ref 100)))
(defn print-accs []
(println " account 1 => " (deref (.balance account1))
" account 2 => " (deref (.balance account2))))
(defn transfer [from to amount]
(dosync
(alter (.balance from) - amount)
(alter (.balance to) + amount)))
(print-accs) ; 100 100
(transfer account1 account2 10)
(print-accs) ; 90 110
是使用transactional memory 或正确实现bank account transfer 的正确示例吗?我是否对字段使用了正确的ref,还是应该对整个Account 实例使用它?
【问题讨论】:
-
transfer中的错字?你传入from to,但稍后使用account[12] -
确实如此。固定