Blob


1 (define (exchange account1 account2)
2 (let ((difference (- (account1 'balance)
3 (account2 'balance))))
4 ((account1 'withdraw) difference)
5 ((account2 'deposit) difference)))
7 (define (make-account-and-serializer balance)
8 (define (withdraw amount)
9 (if (>= balance amount)
10 (begin (set! balance (- balance amount))
11 balance)
12 "Insufficient funds"))
13 (define (deposit amount)
14 (set! balance (+ balance amount))
15 balance)
16 (let ((balance-serializer (make-serializer)))
17 (define (dispatch m)
18 (cond ((eq? m 'withdraw) withdraw)
19 ((eq? m 'deposit) deposit)
20 ((eq? m 'balance) balance)
21 ((eq? m 'serializer) balance-serializer)
22 (else (error "Unknown request -- MAKE-ACCOUT"
23 m))))
24 dispatch))
26 (define (deposit account amount)
27 (let ((s (account 'serializer))
28 (d (account 'deposit)))
29 ((s d) amount)))
31 (define (serialized-exchange account1 account2)
32 (let ((serializer1 (account1 'serializer))
33 (serializer2 (account2 'serializer)))
34 ((serializer1 (serializer2 exchange))
35 account1
36 account2)))
38 ;; Exercise 3.44. Consider the problem of transferring an amount from one account to another. Ben Bitdiddle claims that this can be accomplished with the following procedure, even if there are multiple people concurrently transferring money among multiple accounts, using any account mechanism that serializes deposit and withdrawal transactions, for example, the version of make-account in the text above.
40 (define (transfer from-account to-account amount)
41 ((from-account 'withdraw) amount)
42 ((to-account 'deposit) amount))
44 ;; Louis Reasoner claims that there is a problem here, and that we need to use a more sophisticated method, such as the one required for dealing with the exchange problem. Is Louis right? If not, what is the essential difference between the transfer problem and the exchange problem? (You should assume that the balance in from-account is at least amount.)
46 ;; Louis is wrong. The difference here is that the value in amount is still valid even if other processes change the balances within the two accounts. With difference, if any of the balances change, the amount that needs to be transferred is no longer valid. That is why if two processes alter any of the same accounts, the events cannot be interleaved. However, here, the amount that needs to be transferred will still be valid even if other processes change any of the accounts concurrently.