【SICP練習】114 練習3.38-3.39,sicp3.38-3.39
練習3-38原文
Exercise 3.38. Suppose that Peter, Paul, and Mary share a joint bank account that initially contains 100. Concurrently, Peter deposits 10, Paul withdraws 20, and Mary withdraws half the money in the account, by executing the following commands:
Peter: (set! balance (+ balance 10))
Paul: (set! balance (- balance 20))
Mary: (set! balance (- balance (/ balance 2)))
a. List all the different possible values for balance after these three transactions have been completed, assuming that the banking system forces the three processes to run sequentially in some order.
b. What are some other values that could be produced if the system allows the processes to be interleaved? Draw timing diagrams like the one in figure 3.29 to explain how these values can occur.
分析
a小題中題目假定銀行系統強迫著三個進程按照某種順序方式進行。將3個人(或者說3個進程)全排序有A(3,3)=3X2X1=6種方式。具體為:
Peter (110) -> Paul (90) -> Mary (45)
Peter (110) -> Mary (55) -> Paul (35)
Paul (80) -> Peter (90) -> Mary (45)
Paul (80) -> Mary (40) -> Peter (50)
Mary (50) -> Peter (60) -> Paul (40)
Mary (50) -> Paul (30) -> Peter (40)
b小題參照書中第209頁即可,由於編輯較困難在此就不予列出了。
練習3-39原文
Exercise 3.39. Which of the five possibilities in the parallel execution shown above remain if we instead serialize execution as follows:
(define x 10) (define s (make-serializer)) (parallel-execute (lambda () (set! x ((s (lambda () (* x x)))))) (s (lambda () (set! x (+ x 1)))))
分析
做這道題之前必須理解書中的樣本。另外加入了make-serializer進行序列化後,P1和P2(表示傳入parallel-execute的無參過程)的執行不回交錯進行。題目中的以下兩行代碼均為序列化操作。
((s (lambda () (* x x))))((s (lambda () (set! x (+ x 1)))))
如果將這兩段代碼用LS1和LS2來代替,則題中的代碼簡化為:
(parallel-execute (lambda () (set! x LS1)) LS2)
因此會有2種可能的執行順序:
LS2 - > (set! x LS1)
(set! x LS1) - > LS2
相應的執行結果如下:
1) LS2 - > (set! x (+ x 1)) - > x = 11
(set! x (* x x)) - > x = 121
2) (set! x LS1) - > (set! x (* x x)) - > x = 100
(set! x (+ x 1)) - > x = 101
但還有一種可能,當執行(set! x LS1)時,由於要先執行LS1,而不可能這個操作並未執行完LS2並已經開始了,最後又折回來執行(set! x LS1)。執行順序為:
LS1 - > (set! x LS1) - > LS2 - > (set! x LS1)
不過在第一個(set! x LS1)時,該步驟並未徹底執行完。相應的執行結果為121。
為使本文得到斧正和提問,轉載請註明出處:
http://blog.csdn.net/nomasp
郵箱及Skype:nomasp@outlook.com
Facebook:https://www.facebook.com/yuwang.ke
CSDN部落格:http://blog.csdn.net/nomasp
新浪微博:http://weibo.com/nomasp