From: Ramakrishnan Muthukrishnan Date: Sat, 18 Jun 2011 10:26:56 +0000 (+0530) Subject: solution to 4.48 and 4.49 X-Git-Url: https://git.rkrishnan.org/pf/content/%22file:/%22news.html/vdrive/running.html?a=commitdiff_plain;h=ece04a94fc8a1c3a6c842add106ff083e49b68bf;p=sicp.git solution to 4.48 and 4.49 --- diff --git a/src/sicp/ex4_48.rkt b/src/sicp/ex4_48.rkt new file mode 100644 index 0000000..2163808 --- /dev/null +++ b/src/sicp/ex4_48.rkt @@ -0,0 +1,46 @@ +#lang racket + +#| + +by giving a unique number to each account, we are ordering the access to the account +in a specific manner (say in the ascending order of the number). The reason why deadlock +occurs is be cause of the concurrent access to the accounts in a specific order (Paul +attempts to transfer a1 and a2 while Peter attempts to transfer a2 and a1. With the +suggested change, both will concurrently try to access a1 first but only one of them +will get access while the other will wait until the serializer for a1 is released. + +|# + +(define (make-account-and-serializer 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 'balance) balance) + ((eq? m 'account-number) account-number) + ((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)) + (number1 (account1 'account-number)) + (number2 (account2 'account-number))) + (if (< number1 number2) + ((serializer2 (serializer1 exchange)) + account1 + account2) + ((serializer1 (serializer2 exchange)) + account1 + account2) +)) \ No newline at end of file diff --git a/src/sicp/ex4_49.rkt b/src/sicp/ex4_49.rkt new file mode 100644 index 0000000..b326820 --- /dev/null +++ b/src/sicp/ex4_49.rkt @@ -0,0 +1,11 @@ +#lang racket + +#| + +Process 1 needs access to a shared resource depending on some runtime condition and needs +another resource depending on another condition. + +Consider another similar process being executed concurrently. We cannot determine +the order of the resource acquisition apriori in this case. + +|# \ No newline at end of file