weima learns to program

my attempt to do the exercises in sicp.

Thursday, March 18, 2010

sicp exercise 3.40

;; Exercise 3.40.  Give all possible values of x that can result from executing

;; (define x 10)

;; (parallel-execute (lambda () (set! x (* x x)))
;;                   (lambda () (set! x (* x x x))))

;; Which of these possibilities remain if we instead use serialized procedures:

;; (define x 10)

;; (define s (make-serializer))

;; (parallel-execute (s (lambda () (set! x (* x x))))
;;                   (s (lambda () (set! x (* x x x)))))

(define (make-serializer)
(let ((mutex (make-mutex)))
(lambda (p)
(define (serialized-p . args)
(lock-mutex mutex)
(let ((val (apply p args)))
(unlock-mutex mutex)
val))
serialized-p)))

(define x 10)

(parallel ((lambda () (set! x (* x x))))
((lambda () (set! x (* x x x)))))
(display x) (newline)
;; x can be set to 100, 1000, 10000, 100000, 1000000

(define x 10)

(define s (make-serializer))

(parallel ((s (lambda () (set! x (* x x)))))
((s (lambda () (set! x (* x x x))))))
(display x) (newline)
;; x is set to 1000000