Groups
Groups
Sign in
Groups
Groups
sicp-sig
Conversations
About
Send feedback
Help
연습문제 3.47, 3.48
3 views
Skip to first unread message
준경군
unread,
Feb 20, 2008, 5:16:47 AM
2/20/08
Reply to author
Sign in to reply to author
Forward
Sign in to forward
Delete
You do not have permission to delete messages in this group
Copy link
Report message
Show original message
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to sicp-sig
; 3.47 - a
(define (make-semaphore-mtx maximal)
(let ((count maximal)
(mutex (make-mutex)))
(define (the-sema m)
(cond ((eq? m 'release)
(mutex 'acquire)
(unless (= count maximal)
(set! count (+ 1 count)))
(mutex 'release))
((eq? m 'acquire)
(cond ((> count 0)
(mutex 'acquire)
(set! count (- count 1))
(mutex 'release))
(else
(the-sema 'acquire))))
(else
(error "Unknown request -- " m))))
the-sema))
; 3.47 - b
(define (loop-test-and-set! cell)
(if (test-and-set! cell)
(loop-test-and-set! cell)))
(define (make-semaphore-ts maximal)
(let ((count maximal)
(guard (list #f)))
(define (the-sema m)
(cond ((eq? m 'release)
(loop-test-and-set! guard)
(unless (= count maximal)
(set! count (+ 1 count)))
(clear! guard))
((eq? m 'acquire)
(cond
((> count 0)
(loop-test-and-set! guard)
(set! count (- count 1))
(clear! guard))
(else
(the-sema 'acquire))))
(else
(error "Unknown request -- " m))))
the-sema))
; 3.48
(define (make-account number balance)
(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 'number) number)
((eq? m 'balance) balance)
((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)))
(if (< (account1 'number) (account2 'number))
((serializer2 (serializer1 exchange))
account1 account2)
((serializer1 (serializer2 exchange))
account1 account2))))
Reply all
Reply to author
Forward
0 new messages