练习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
版权声明:本文为 NoMasp柯于旺 原创文章,如需转载请联系本人。