Suppose multiple processes run sequentially and each exchanges the balances of
two accounts. Because the processes are run sequentially they cannot interfere
with each other and the result is the same as a sequences of swaps made by a
single process. Composing swaps together creates a permutation and at the end
of a sequence of swaps the balances are still a permutation of $10, $20, $30.
(define (exchange account1 account2)
(let ((difference (- (account1 'balance)
(account2 'balance))))
((account1 'withdraw) difference)
((account2 'deposit) difference)))
The balances can change to have different values than $10, $20, $30 if the
following order of events happens.
- Accounts A, B, C initially have balances $10, $20, $30
- Process P1 starts exchanging C and A by withdrawing $20 from C resulting in
intermediate balances $10, $20, $10
- Process P2 exchanges B and A resulting in balances $20, $10, $10
- Process P1 deposits $20 in A resulting in balances $40, $10, $10
Because each withdrawal is eventually followed by a deposit for of the same
amount, money is conserved and the final - but not intermediate - sum of the
balances will remain the same.
If withdrawals and deposits are not serialized, money can disappear. Consider
the following sequence of events.
- P1 starts exchanging the balances of B and A by withdrawing $10 from B and
starts a deposit in A by reading the balance $10 from A.
The balances are: $10, $10, $30
- P2 runs and exchanges the balances of C and A.
The balances are: $30, $10, $10
- P1 finishes by writing $20 = $10 + $10 to account A.
The balances are: $20, $10, $10