【SICP练习】115 练习3.41

本文探讨了银行账户在并发操作下的异常行为可能性。通过分析不同进程对账户余额进行存取操作时的四种执行顺序,得出结论认为Ben对于未同步访问账户余额可能导致异常行为的担忧并无必要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

练习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.youkuaiyun.com/nomasp


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值