]> git.rkrishnan.org Git - sicp.git/blob - src/sicp/ex3_47.rkt
Lazy version of evaluator and tests.
[sicp.git] / src / sicp / ex3_47.rkt
1 #lang racket
2
3 ;; semaphore implementation using mutex
4 (define (make-mutex)
5   (let ([cell (mcons #f '())])
6     (define (the-mutex m)
7       (cond [(eq? m 'acquire)
8              (when (test-and-set! cell)
9                (the-mutex 'acquire))] ;; loop till we acquire the mutex
10             [(eq? m 'release) (clear! cell)]))
11     the-mutex))
12
13 (define (clear! cell)
14   (set-mcar! cell #f))
15
16 (define (test-and-set! cell)
17   (if (mcar cell)
18       #t
19       (begin (set-mcar! cell #t)
20              #f)))
21
22 ;; semaphore implementation
23 (define (make-semaphore n)
24   (let ([cell 0]
25         [mutex (make-mutex)])
26     (define (the-semaphore s)
27       (cond [(eq? s 'acquire)
28              (mutex 'acquire)
29              (if (>= (+ cell 1) n)
30                  (begin
31                    (mutex 'release)
32                    (the-semaphore 'acquire))
33                  (begin
34                    (set! cell (+ cell 1))
35                    (mutex 'release)))]
36             [(eq? s 'release)
37              (mutex 'acquire)
38              (when (> cell 0)             
39                (set! cell (- cell 1)))
40              (mutex 'release)]))
41     the-semaphore))
42
43 ;; using test-and-set!
44 (define (make-semaphore n)
45   (let ([cell 0]
46         [flag #f])
47     (define (the-semaphore s)
48       (cond [(eq? s 'acquire)
49              (if (test-and-set! flag)
50                  (the-semaphore 'acquire))
51              (if (>= (+ cell 1) n)
52                  (begin
53                    (clear! flag)
54                    (the-semaphore 'acquire))
55                  (begin
56                    (set! cell (+ cell 1))
57                    (clear flag)))]
58             [(eq? s 'release)
59              (if (test-and-set! flag)
60                  (the-semaphore 'acquire))
61              (when (> cell 0)             
62                (set! cell (- cell 1)))
63              (clear! flag)]))
64     the-semaphore))