Skip to content

Commit

Permalink
SBCL: try to make ACQUIRE-LOCK and RELEASE-LOCK interrupt-safe
Browse files Browse the repository at this point in the history
  • Loading branch information
sionescu committed Mar 12, 2024
1 parent 666b583 commit 4c3914b
Showing 1 changed file with 33 additions and 2 deletions.
35 changes: 33 additions & 2 deletions apiv2/impl-sbcl.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,42 @@
(defun %make-lock (name)
(sb-thread:make-mutex :name name))

(defun %try-lock (lock)
(sb-sys:without-interrupts
(sb-thread:grab-mutex lock :waitp nil)))

(defun %lock (lock)
(sb-sys:without-interrupts
(sb-sys:allow-with-interrupts
(loop :while (not (sb-thread:grab-mutex lock :waitp t)))
t)))

(defun %timedlock (lock timeout)
(let ((deadline (+ (get-internal-real-time)
(* internal-time-units-per-second
timeout))))
(sb-sys:without-interrupts
(sb-sys:allow-with-interrupts
(loop :while (not (sb-thread:grab-mutex lock :waitp t :timeout timeout))
:for now := (get-internal-real-time)
:do (if (>= now deadline)
(return-from %timedlock nil)
(setf timeout (/ (- deadline now)
internal-time-units-per-second))))
t))))

(defun %acquire-lock (lock waitp timeout)
(sb-thread:grab-mutex lock :waitp waitp :timeout timeout))
(cond
((not waitp)
(%try-lock lock))
((null timeout)
(%lock lock))
(t
(%timedlock lock timeout))))

(defun %release-lock (lock)
(sb-thread:release-mutex lock))
(sb-sys:without-interrupts
(sb-thread:release-mutex lock)))

(defmacro %with-lock ((place timeout) &body body)
`(sb-thread:with-mutex (,place :timeout ,timeout) ,@body))
Expand Down

0 comments on commit 4c3914b

Please sign in to comment.