我是clojure
的新手,我正在尝试实施经典并发示例,即bank account transfer
。我想用transactional memory
来实现它。clojure银行帐户汇款示例
这里是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
实例?
错字?你传入'from to',但后来使用'account [12]' – cfrick
哦。固定 – lapots