首页 > 其他 > 详细

【SICP练习】115 练习3.41

时间:2015-03-26 23:39:30      阅读:287      评论:0      收藏:0      [点我收藏+]

练习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并没有担心的必要。

【SICP练习】115 练习3.41

原文:http://blog.csdn.net/nomasp/article/details/44654313

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!