Advertisement
timothy235

sicp-3-4-1-the-nature-of-time-in-concurrent-systems

Mar 3rd, 2017
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.56 KB | None | 0 0
  1. #lang racket
  2.  
  3. ;;;;;;;;;;
  4. ;; 3.38 ;;
  5. ;;;;;;;;;;
  6.  
  7. (define (make-account initial-balance)
  8.   (define balance initial-balance)
  9.   (define (deposit amount) (set! balance (+ balance amount)))
  10.   (define (withdraw amount) (set! balance (- balance amount)))
  11.   (define (halve) (set! balance (/ balance 2)))
  12.   (define (dispatch m)
  13.     (cond [(eq? m 'deposit) deposit]
  14.           [(eq? m 'withdraw) withdraw]
  15.           [(eq? m 'halve) halve]
  16.           [(eq? m 'balance) balance]
  17.           [else (error "Unknown message -- DISPATCH" m)]))
  18.   dispatch)
  19.  
  20. (define (peter acct) ((acct 'deposit) 10))
  21. (define (paul acct) ((acct 'withdraw) 20))
  22. (define (mary acct) ((acct 'halve)))
  23.  
  24. ;; What are the possible final balances after allowing these three transactions to
  25. ;; be completed sequentially in any order?
  26.  
  27. (define (test sequence)
  28.   (define test-account (make-account 100))
  29.   (for ([p sequence]) (p test-account))
  30.   (test-account 'balance))
  31.  
  32. (for/list ([seq (in-permutations (list peter paul mary))])
  33.           (test seq))
  34. ;; '(40 50 40 35 45 45)
  35.  
  36. ;; What are some other values that could be produced if the processes could be
  37. ;; interleaved?
  38.  
  39. ;; Interleaving the processes allows us to ignore one or two commands because
  40. ;; those commands could always be executed between the third command's read and
  41. ;; write operations.  So one new value would be 110, obtained by the following
  42. ;; sequence of events:
  43.  
  44. ;; peter reads balance = 100
  45. ;; peter computes (+ balance 10) and gets 110
  46. ;; paul does his transaction
  47. ;; mary does her transaction
  48. ;; peter sets balance to 110
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement