이 문제는 엇걸림 상태(교착 상태, deadlock)을 해소하는 방법 중 하나로

각 계정에 번호를 매겨 작은 번호부터 움켜쥐도록 만드는 방법이 있습니다.

 

이 방법을 쓰면 왜 deadlock을 피할 수 있는지 말하겠습니다.

예로 든 Paul과 Peter의 경우를 살펴보면

Paul은 a1을 쥐고 a2에 접근하고, Peter는 a2를 쥐고 a1에 접근을 합니다.

따라서 deadlock이 되고맙니다.

 

하지만 위와 같은 방법을 쓰게 된다면

Paul과 Peter 모두 번호가 작은 계정을 먼저 얻으려고 할 것입니다.

만약 a1이 1, a2가 2의 값을 가지고 Paul이 a1을 획득하였다면

Peter는 a1이 놓아지기를 기다립니다.

놓아지는 시기는 Paul이 일을 마쳤을 때이니 그 때 Peter가 접근하여도 문제 없습니다.

 

 

여기에 맞춰 serialized-exchange와 make-account 프로시저를 수정하였습니다.

 

하지만 이 역시 동작을 시킬 수 없어 제대로 하였는지 잘 모르겠습니다.

 

 

참조

해럴드 애빌슨, 김재우 역, <컴퓨터 프로그램의 구조와 해석>, 인사이트, 2007, pp. 409

 

 

(define (serialized-exchange account1 account2)
  (let ((serializer1 (account1 'serializer))
        (serializer2 (account2 'serializer))
        (a1_number (account1 'number))
        (a2_number (account2 'number)))
    (if (< a1_number a2_number)
        ((serializer1 (serializer2 exchange))
         account1
         account2)
        ((serializer2 (serializer1 exchange))
         account2
         account1))))

(define (make-account-and-serializer balance identification_number)
  (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 'serializer) balance-serializer)
            ((eq? m 'number) identification_number)
            (else (error "Unknown request -- MAKE-ACCOUNT"
                         m))))
    dispatch))

크리에이티브 커먼즈 라이선스
Creative Commons License

글에 잘못된 점, 다른 점, 부족한 점이 있다면 지적해주세요.
댓글, 트랙백, 메일 모두 고맙습니다.

트랙백 주소 :: http://nosyu.pe.kr/trackback/1606

댓글을 달아 주세요

[로그인][오픈아이디란?]