我是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