【SICP练习】116 练习3.42

练习3-42

原文

Exercise 3.42. Ben Bitdiddle suggests that it’s a waste of time to create a new serialized procedure in response to every withdraw and deposit message. He says that make-account could be changed so that the calls to protected are done outside the dispatch procedure. That is, an account would return the same serialized procedure (which was created at the same time as the account) each time it is asked for a withdrawal procedure.

(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)  
   (let ((protected (make-serializer)))  
     (let ((protected-withdraw (protected withdraw))            
           (protected-deposit (protected deposit)))  
        (define (dispatch m)      
          (cond ((eq? m 'withdraw) protected-withdraw) ((eq? m 'deposit) protected-deposit) ((eq? m 'balance) balance) (else (error "Unknown request -- MAKE-ACCOUNT" m))))   
   dispatch)))

Is this a safe change to make? In particular, is there any difference in what concurrency is allowed by these two versions of make-account ?

分析

对于Ben的make-account函数而言,如果有以下5种操作:

(protected-deposit 10)
(protected-deposit 20)
(protected-deposit 40)
(protected-deposit 80)
(protected-deposit 160)

由于它们都会调用同一个protected-deposit串行化对象来调用请求,这意味着在处理第一个操作时,其他4个操作也即开始并发地运行,那么除了第一个操作之外,其余操作均会出错。这是因为运行中的串行化进程是不能被其他的过程所干扰的。

相比之下,原版的make-account函数则会在求值多种操作时,将所有的表达式都放进串行化组protected中,这样它们就可以并发的执行而不会被彼此所干扰。



感谢访问,希望对您有所帮助。 欢迎关注或收藏、评论或点赞。


为使本文得到斧正和提问,转载请注明出处:
http://blog.csdn.net/nomasp


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值