Blame


1 665c255d 2023-08-04 jrmu ;; 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):
2 665c255d 2023-08-04 jrmu
3 665c255d 2023-08-04 jrmu (define (make-account balance)
4 665c255d 2023-08-04 jrmu (define (withdraw amount)
5 665c255d 2023-08-04 jrmu (if (>= balance amount)
6 665c255d 2023-08-04 jrmu (begin (set! balance (- balance amount))
7 665c255d 2023-08-04 jrmu balance)
8 665c255d 2023-08-04 jrmu "Insufficient funds"))
9 665c255d 2023-08-04 jrmu (define (deposit amount)
10 665c255d 2023-08-04 jrmu (set! balance (+ balance amount))
11 665c255d 2023-08-04 jrmu balance)
12 665c255d 2023-08-04 jrmu ;; continued on next page
13 665c255d 2023-08-04 jrmu
14 665c255d 2023-08-04 jrmu (let ((protected (make-serializer)))
15 665c255d 2023-08-04 jrmu (define (dispatch m)
16 665c255d 2023-08-04 jrmu (cond ((eq? m 'withdraw) (protected withdraw))
17 665c255d 2023-08-04 jrmu ((eq? m 'deposit) (protected deposit))
18 665c255d 2023-08-04 jrmu ((eq? m 'balance)
19 665c255d 2023-08-04 jrmu ((protected (lambda () balance)))) ; serialized
20 665c255d 2023-08-04 jrmu (else (error "Unknown request -- MAKE-ACCOUNT"
21 665c255d 2023-08-04 jrmu m))))
22 665c255d 2023-08-04 jrmu dispatch))
23 665c255d 2023-08-04 jrmu
24 665c255d 2023-08-04 jrmu ;; 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?
25 665c255d 2023-08-04 jrmu
26 665c255d 2023-08-04 jrmu
27 665c255d 2023-08-04 jrmu ;; 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.
28 665c255d 2023-08-04 jrmu
29 665c255d 2023-08-04 jrmu ;; 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.