]> git.rkrishnan.org Git - sicp.git/commitdiff
mutex discussions in the section
authorRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Sat, 18 Jun 2011 09:17:29 +0000 (14:47 +0530)
committerRamakrishnan Muthukrishnan <vu3rdd@gmail.com>
Sat, 18 Jun 2011 09:17:29 +0000 (14:47 +0530)
src/sicp/mutex.rkt [new file with mode: 0644]

diff --git a/src/sicp/mutex.rkt b/src/sicp/mutex.rkt
new file mode 100644 (file)
index 0000000..6937404
--- /dev/null
@@ -0,0 +1,29 @@
+#lang racket
+
+(define (make-serializer)
+  (let ([mutex (make-mutex)])
+    (lambda (p)
+      (define (serialized-p . args)
+        (mutex 'acquire)
+        (let ([val (apply p args)])
+          (mutex 'release)
+          val))
+      serialized-p)))
+          
+(define (make-mutex)
+  (let ([cell (mcons #f '())])
+    (define (the-mutex m)
+      (cond [(eq? m 'acquire)
+             (when (test-and-set! cell)
+               (the-mutex 'acquire))] ;; loop till we acquire the mutex
+            [(eq? m 'release) (clear! cell)]))
+    the-mutex))
+
+(define (clear! cell)
+  (set-mcar! cell #f))
+
+(define (test-and-set! cell)
+  (if (mcar cell)
+      #t
+      (begin (set-mcar! cell #t)
+             #f)))