0.9.13.22:
[sbcl.git] / src / code / thread.lisp
1 ;;;; support for threads needed at cross-compile time
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
11
12 (in-package "SB!THREAD")
13
14 (def!struct mutex
15   #!+sb-doc
16   "Mutex type."
17   (name nil :type (or null simple-string))
18   (value nil)
19   #!+(and sb-lutex sb-thread)
20   (lutex (make-lutex)))
21
22 (def!struct spinlock
23   #!+sb-doc
24   "Spinlock type."
25   (name nil :type (or null simple-string))
26   (value 0))
27
28 (sb!xc:defmacro with-mutex ((mutex &key (value '*current-thread*) (wait-p t))
29                             &body body)
30   #!+sb-doc
31   "Acquire MUTEX for the dynamic scope of BODY, setting it to
32 NEW-VALUE or some suitable default value if NIL.  If WAIT-P is non-NIL
33 and the mutex is in use, sleep until it is available"
34   #!-sb-thread (declare (ignore mutex value wait-p))
35   #!+sb-thread
36   (with-unique-names (got mutex1)
37     `(let ((,mutex1 ,mutex)
38            ,got)
39        (/show0 "WITH-MUTEX")
40        (unwind-protect
41             ;; FIXME: async unwind in SETQ form
42             (when (setq ,got (get-mutex ,mutex1 ,value ,wait-p))
43               (locally
44                   ,@body))
45          (when ,got
46            (release-mutex ,mutex1)))))
47   ;; KLUDGE: this separate expansion for (NOT SB-THREAD) is not
48   ;; strictly necessary; GET-MUTEX and RELEASE-MUTEX are implemented.
49   ;; However, there would be a (possibly slight) performance hit in
50   ;; using them.
51   #!-sb-thread
52   `(locally ,@body))
53
54 (sb!xc:defmacro with-recursive-lock ((mutex) &body body)
55   #!+sb-doc
56   "Acquires MUTEX for the dynamic scope of BODY. Within that scope
57 further recursive lock attempts for the same mutex succeed. It is
58 allowed to mix WITH-MUTEX and WITH-RECURSIVE-LOCK for the same mutex
59 provided the default value is used for the mutex."
60   #!-sb-thread
61   (declare (ignore mutex))
62   #!+sb-thread
63   (with-unique-names (mutex1 inner-lock-p)
64     `(let* ((,mutex1 ,mutex)
65             (,inner-lock-p (eq (mutex-value ,mutex1) *current-thread*)))
66        (unwind-protect
67             (progn
68               (unless ,inner-lock-p
69                 (get-mutex ,mutex1))
70               (locally
71                   ,@body))
72          (unless ,inner-lock-p
73            (release-mutex ,mutex1)))))
74   #!-sb-thread
75   `(locally ,@body))