-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3_47.scm
51 lines (47 loc) · 1.3 KB
/
3_47.scm
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
#lang sicp
;; a. in terms of mutexes
(define (make-semaphore n)
(let ((mutex (make-mutex)))
(define (the-semaphore m)
(cond ((eq? m 'acquire)
(begin
(mutex 'acquire)
(if (> n 0)
(begin
(set! n (- n 1))
(mutex 'release))
(begin
(mutex 'release)
(the-semaphore 'acquire)))))
((eq? m 'release)
(begin
(mutex 'acquire)
(set! n (+ n 1))
(mutex 'release)))))
the-semaphore))
;; b. in terms of atomic test-and-set! operations
(define (make-semaphore n)
(define (the-semaphore m)
(cond ((eq? m 'acquire)
(if (test-and-dec! n)
(the-semaphore 'acquire)))
((eq? m 'release)
(if (atomic-inc! n)
(the-semaphore 'release)))))
the-semaphore)
(define (test-and-dec! n)
(let ((cell (list #f)))
(if (= n 0)
#t
(if (test-and-set! cell)
#t
(begin
(set! n (- n 1))
(clear! cell))))))
(define (atomic-inc! n)
(let ((cell (list #f)))
(if (test-and-set! cell)
#t
(begin
(set! n (+ n 1))
(clear! cell)))))