-
Notifications
You must be signed in to change notification settings - Fork 2
/
rwlock.lisp
53 lines (46 loc) · 1.72 KB
/
rwlock.lisp
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
52
53
(in-package #:cl-wasm-runtime)
(defstruct rwlock
(read-lock (bt:make-lock))
(write-lock (bt:make-lock))
(retry-lock (bt:make-lock))
(resource (bt:make-lock))
(read-count 0)
(write-count 0))
(defun read-lock-begin (rwlock)
(bt:acquire-lock (rwlock-retry-lock rwlock))
(bt:acquire-lock (rwlock-read-lock rwlock))
(when (= 1 (incf (rwlock-read-count rwlock)))
(bt:acquire-lock (rwlock-resource rwlock)))
(bt:release-lock (rwlock-read-lock rwlock))
(bt:release-lock (rwlock-retry-lock rwlock)))
(defun read-lock-end (rwlock)
(bt:acquire-lock (rwlock-read-lock rwlock))
(when (= 0 (decf (rwlock-read-count rwlock)))
(bt:release-lock (rwlock-resource rwlock)))
(bt:release-lock (rwlock-read-lock rwlock)))
(defmacro with-read-lock (rwlock &body body)
(alexandria:with-gensyms (rwlock%)
`(let ((,rwlock% ,rwlock))
(read-lock-begin ,rwlock%)
(unwind-protect
(progn ,@body)
(read-lock-end ,rwlock%)))))
(defun write-lock-begin (rwlock)
(bt:acquire-lock (rwlock-write-lock rwlock))
(when (= 1 (incf (rwlock-write-count rwlock)))
(bt:acquire-lock (rwlock-retry-lock rwlock)))
(bt:release-lock (rwlock-write-lock rwlock))
(bt:acquire-lock (rwlock-resource rwlock)))
(defun write-lock-end (rwlock)
(bt:release-lock (rwlock-resource rwlock))
(bt:acquire-lock (rwlock-write-lock rwlock))
(when (= 0 (decf (rwlock-write-count rwlock)))
(bt:release-lock (rwlock-retry-lock rwlock)))
(bt:release-lock (rwlock-write-lock rwlock)))
(defmacro with-write-lock (rwlock &body body)
(alexandria:with-gensyms (rwlock%)
`(let ((,rwlock% ,rwlock))
(write-lock-begin ,rwlock%)
(unwind-protect
(progn ,@body)
(write-lock-end ,rwlock%)))))