Blame


1 665c255d 2023-08-04 jrmu (define (make-serializer)
2 665c255d 2023-08-04 jrmu (let ((mutex (make-mutex)))
3 665c255d 2023-08-04 jrmu (lambda (p)
4 665c255d 2023-08-04 jrmu (define (serialized-p . args)
5 665c255d 2023-08-04 jrmu (mutex 'acquire)
6 665c255d 2023-08-04 jrmu (let ((val (apply p args)))
7 665c255d 2023-08-04 jrmu (mutex 'release)
8 665c255d 2023-08-04 jrmu val))
9 665c255d 2023-08-04 jrmu serialized-p)))
10 665c255d 2023-08-04 jrmu
11 665c255d 2023-08-04 jrmu (define (make-mutex)
12 665c255d 2023-08-04 jrmu (let ((cell (list false)))
13 665c255d 2023-08-04 jrmu (define (the-mutex m)
14 665c255d 2023-08-04 jrmu (cond ((eq? m 'acquire) (if (test-and-set! cell)
15 665c255d 2023-08-04 jrmu (the-mutex 'acquire)))
16 665c255d 2023-08-04 jrmu ((eq? m 'release) (clear! cell))))
17 665c255d 2023-08-04 jrmu the-mutex))
18 665c255d 2023-08-04 jrmu
19 665c255d 2023-08-04 jrmu (define (clear! cell)
20 665c255d 2023-08-04 jrmu (set-car! cell false))
21 665c255d 2023-08-04 jrmu ;; (define (test-and-set! cell)
22 665c255d 2023-08-04 jrmu ;; (if (car cell)
23 665c255d 2023-08-04 jrmu ;; true
24 665c255d 2023-08-04 jrmu ;; (begin (set-car! cell true)
25 665c255d 2023-08-04 jrmu ;; false)))
26 665c255d 2023-08-04 jrmu (define (test-and-set! cell)
27 665c255d 2023-08-04 jrmu (without-interrupts
28 665c255d 2023-08-04 jrmu (lambda ()
29 665c255d 2023-08-04 jrmu (if (car cell)
30 665c255d 2023-08-04 jrmu true
31 665c255d 2023-08-04 jrmu (begin (set-car! cell true)
32 665c255d 2023-08-04 jrmu false)))))
33 665c255d 2023-08-04 jrmu
34 665c255d 2023-08-04 jrmu ;; Exercise 3.46. Suppose that we implement test-and-set! using an ordinary procedure as shown in the text, without attempting to make the operation atomic. Draw a timing diagram like the one in figure 3.29 to demonstrate how the mutex implementation can fail by allowing two processes to acquire the mutex at the same time.
35 665c255d 2023-08-04 jrmu
36 665c255d 2023-08-04 jrmu ;; The same mutex might be acquired at the same time by two different processes. For example, both may check (car cell) right after the other. It appears to both processes as though the mutex were free to be acquired, so both set the cell to true and think that they have exclusive access tothe mutex.