sicp-3-4

Posted on 2015-03-02 01:03:22 +0900 in SICP Lisp

3.39

  1. 101: P1 , P2
  2. 121: P2, P1
  3. 100: P1 computes (* x x), then P2 completes and sets x to 101, then P1 executes the assignment.

3.41

As withdraw and diposit are both single modification operations, it is not necessary to protect the balance value, as it would always be valid.

3.42

It seems both of them would work.

3.43

The sum would be kept just because each account is consistent individually.

3.44

Ben is correct. Exchange requires consitent states for both accounts, while transfer would be fine as long as the sum of two accounts is correct.

3.45

serialized-exchange has locked both accounts, which makes it impossible to run deposit or withdraw.

3.46

If atomic is not guaranteed, then multiple process can gain the same mutex at the same time which would result in wrong result.

3.47

(define (make-semaphore n)
  (let ((the-mutex (make-mutex))
        (count 0))
    (define (the-semaphore m)
      (cond ((eq? m 'acquire)
             (the-mutex 'acquire)
             (if (= count n) ; full, have to wait
               (begin
                 (the-mutex 'release)
                 (the-semaphore 'acquire))
               (begin
                 (set! count (+ count 1))
                 (the-mutex 'release))))
            ((eq? m 'release)
             (the-mux 'require)
             (set! count (- count 1))
             (the-mux 'release))))
    the-semaphore))

3.48

(define (make-account-and-serializer balance id)
  (define (withdraw amount)
    (if (>= balance amount)
        (begin (set! balance (- balance amount))
               balance)
        "Insufficient funds"))
  (define (deposit amount)
    (set! balance (+ balance amount))
    balance)
  (let ((balance-serializer (make-serializer)))
    (define (dispatch m)
      (cond ((eq? m 'withdraw) withdraw)
            ((eq? m 'deposit) deposit)
            ((eq? m 'balance) balance)
            ((eq? m 'id) id)
            ((eq? m 'serializer) balance-serializer)
            (else (error "Unknown request -- MAKE-ACCOUNT"
                         m))))
    dispatch))

(define (serialized-exchange account1 account2)
  (let ((serializer1 (account1 'serializer))
        (serializer2 (account2 'serializer))
        (id1 ((account1 'id1)))
        (id2 ((account1 'id2))))
    (if (< id1 id2))
    ((serializer2 (serializer1 exchange))
     account1
     account2)
    ((serializer1 (serializer2 exchange))
     account1
     account2)))
----------------------------------- 本文内容遵从CC版权协议转载请注明出自kamelzcs -----------------------------------
«  | sicp-3-3-5 »

Hide Comments

comments powered by Disqus