【SICP練習】115 練習3.41,sicp練習1153.41
練習3-41原文
Exercise 3.41. Ben Bitdiddle worries that it would be better to implement the bank account as follows (where the commented line has been changed):
(define (make-account balance) (define (withdraw amount) (if (>= balance amount) (begin (set! balance (- balance amount)) balance) "Insufficient funds")) (define (deposit amount) (set! balance (+ balance amount)) balance) ;; continued on next page (let ((protected (make-serializer))) (define (dispatch m) (cond ((eq? m 'withdraw) (protected withdraw)) ((eq? m 'deposit) (protected deposit)) ((eq? m 'balance) ((protected (lambda () balance)))) ; serialized (else (error "Unknown request -- MAKE-ACCOUNT" m)))) dispatch))
because allowing unserialized access to the bank balance can result in anomalous behavior. Do you agree?
Is there any scenario that demonstrates Ben’s concern?
分析
假設有((protected withdraw) 100)和((protected deposit) 50)兩個進程分別和balance並存執行。則會有4種可能的執行順序。
withdraw - > balance 操作時,首先將餘額設定為0,然後返回balance得到0。
balance - > withdraw操作時,首先balance會得到100,然後執行withdraw操作得到0。
deposit - > balance操作時,首先將餘額設定為150,然後返回balance得到150。
balance - > deposit操作時,首先balance會得到100,然後deposit操作得到150。
由此可見Ben並沒有擔心的必要。
為使本文得到斧正和提問,轉載請註明出處:
http://blog.csdn.net/nomasp
郵箱及Skype:nomasp@outlook.com
Facebook:https://www.facebook.com/yuwang.ke
CSDN部落格:http://blog.csdn.net/nomasp
新浪微博:http://weibo.com/nomasp