1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
;; a
(define (make-semaphore n)
(let ((mutex (make-mutex))
(original-n n))
(define (acquire)
(mutex 'acquire)
(if (> n 0)
(begin (set! n (- n 1))
(mutex 'release)
'ok)
(begin (mutex 'release)
(acquire))))
(define (release)
(if (< n original-n)
(begin (mutex 'acquire)
(set! n (+ n 1))
(mutex 'release)
'ok)))
(define (the-semaphore m)
(cond ((eq? m 'acquire)
(acquire))
((eq? m 'release)
(release))))
the-semaphore))
;; b
(define (make-semaphore n)
(let ((original-n n))
(define (acquire)
(if (test-and-set! n)
(acquire)
'ok))
(define (release)
(if (< n original-n)
(begin
(set! n (+ n 1))
'ok)))
(define (the-semaphore m)
(cond ((eq? m 'acquire)
(acquire))
((eq? m 'release)
(release))))
the-semaphore))
(define (test-and-set! n)
(if (= n 0)
true
(begin (set! n (- n 1))
false)))
|