Blob


1 ;; 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):
3 (define (make-account balance)
4 (define (withdraw amount)
5 (if (>= balance amount)
6 (begin (set! balance (- balance amount))
7 balance)
8 "Insufficient funds"))
9 (define (deposit amount)
10 (set! balance (+ balance amount))
11 balance)
12 ;; continued on next page
14 (let ((protected (make-serializer)))
15 (define (dispatch m)
16 (cond ((eq? m 'withdraw) (protected withdraw))
17 ((eq? m 'deposit) (protected deposit))
18 ((eq? m 'balance)
19 ((protected (lambda () balance)))) ; serialized
20 (else (error "Unknown request -- MAKE-ACCOUNT"
21 m))))
22 dispatch))
24 ;; 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?
27 ;; No, this is unnecessary. By the time you use the balance value, it might possibly be out-of-date anyway, whether you serialize it or not.
29 ;; The reason there is no need to serialize is because the result of balance does not depend on any other pieces of shared state that might be changed after the procedure begins but before it completes. There is no way to interleave events (since there is only one instruction), and so the result will be the same as though the processes were executed sequentially.