1.0.37.15: Make SB-THREAD:TRY-SEMAPHORE decrement count by N.
[sbcl.git] / src / code / target-thread.lisp
1 ;;;; support for threads in the target machine
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 ;;; Conditions
15
16 (define-condition thread-error (error)
17   ((thread :reader thread-error-thread :initarg :thread))
18   #!+sb-doc
19   (:documentation
20    "Conditions of type THREAD-ERROR are signalled when thread operations fail.
21 The offending thread is initialized by the :THREAD initialization argument and
22 read by the function THREAD-ERROR-THREAD."))
23
24 #!+sb-doc
25 (setf
26  (fdocumentation 'thread-error-thread 'function)
27  "Return the offending thread that the THREAD-ERROR pertains to.")
28
29 (define-condition symbol-value-in-thread-error (cell-error thread-error)
30   ((info :reader symbol-value-in-thread-error-info :initarg :info))
31   (:report
32    (lambda (condition stream)
33      (destructuring-bind (op problem)
34          (symbol-value-in-thread-error-info condition)
35        (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
36                op
37                (cell-error-name condition)
38                (thread-error-thread condition)
39                (ecase problem
40                  (:unbound-in-thread "the symbol is unbound in thread.")
41                  (:no-tls-value "the symbol has no thread-local value.")
42                  (:thread-dead "the thread has exited.")
43                  (:invalid-tls-value "the thread-local value is not valid."))))))
44   #!+sb-doc
45   (:documentation
46    "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
47 the symbol not having a thread-local value, or the target thread having
48 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
49 offending thread using THREAD-ERROR-THREAD."))
50
51 (define-condition join-thread-error (thread-error) ()
52   (:report (lambda (c s)
53              (format s "Joining thread failed: thread ~A ~
54                         did not return normally."
55                      (thread-error-thread c))))
56   #!+sb-doc
57   (:documentation
58    "Signalled when joining a thread fails due to abnormal exit of the thread
59 to be joined. The offending thread can be accessed using
60 THREAD-ERROR-THREAD."))
61
62 (defun join-thread-error-thread (condition)
63   (thread-error-thread condition))
64 (define-compiler-macro join-thread-error-thread (condition)
65   (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
66   `(thread-error-thread ,condition))
67
68 #!+sb-doc
69 (setf
70  (fdocumentation 'join-thread-error-thread 'function)
71  "The thread that we failed to join. Deprecated, use THREAD-ERROR-THREAD
72 instead.")
73
74 (define-condition interrupt-thread-error (thread-error) ()
75   (:report (lambda (c s)
76              (format s "Interrupt thread failed: thread ~A has exited."
77                      (thread-error-thread c))))
78   #!+sb-doc
79   (:documentation
80    "Signalled when interrupting a thread fails because the thread has already
81 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
82
83 (defun interrupt-thread-error-thread (condition)
84   (thread-error-thread condition))
85 (define-compiler-macro interrupt-thread-error-thread (condition)
86   (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
87   `(thread-error-thread ,condition))
88
89 #!+sb-doc
90 (setf
91  (fdocumentation 'interrupt-thread-error-thread 'function)
92  "The thread that was not interrupted. Deprecated, use THREAD-ERROR-THREAD
93 instead.")
94
95 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
96 ;;; necessary because threads are only supported with the conservative
97 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
98 ;;; are treated as references.
99
100 ;;; set the doc here because in early-thread FDOCUMENTATION is not
101 ;;; available, yet
102 #!+sb-doc
103 (setf (fdocumentation '*current-thread* 'variable)
104       "Bound in each thread to the thread itself.")
105
106 #!+sb-doc
107 (setf
108  (fdocumentation 'thread-name 'function)
109  "Name of the thread. Can be assigned to using SETF. Thread names can be
110 arbitrary printable objects, and need not be unique.")
111
112 (def!method print-object ((thread thread) stream)
113   (print-unreadable-object (thread stream :type t :identity t)
114     (let* ((cookie (list thread))
115            (info (if (thread-alive-p thread)
116                      :running
117                      (multiple-value-list
118                       (join-thread thread :default cookie))))
119            (state (if (eq :running info)
120                       info
121                       (if (eq cookie (car info))
122                           :aborted
123                           :finished)))
124            (values (when (eq :finished state) info)))
125       (format stream
126               "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
127               (thread-name thread)
128               (eq :finished state)
129               state
130               values))))
131
132 (defun thread-alive-p (thread)
133   #!+sb-doc
134   "Return T if THREAD is still alive. Note that the return value is
135 potentially stale even before the function returns, as the thread may exit at
136 any time."
137   (thread-%alive-p thread))
138
139 ;; A thread is eligible for gc iff it has finished and there are no
140 ;; more references to it. This list is supposed to keep a reference to
141 ;; all running threads.
142 (defvar *all-threads* ())
143 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
144
145 (defvar *default-alloc-signal* nil)
146
147 (defmacro with-all-threads-lock (&body body)
148   `(with-system-mutex (*all-threads-lock*)
149      ,@body))
150
151 (defun list-all-threads ()
152   #!+sb-doc
153   "Return a list of the live threads. Note that the return value is
154 potentially stale even before the function returns, as new threads may be
155 created and old ones may exit at any time."
156   (with-all-threads-lock
157     (copy-list *all-threads*)))
158
159 (declaim (inline current-thread-sap))
160 (defun current-thread-sap ()
161   (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
162
163 (declaim (inline current-thread-os-thread))
164 (defun current-thread-os-thread ()
165   #!+sb-thread
166   (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
167   #!-sb-thread
168   0)
169
170 (defun init-initial-thread ()
171   (/show0 "Entering INIT-INITIAL-THREAD")
172   (let ((initial-thread (%make-thread :name "initial thread"
173                                       :%alive-p t
174                                       :os-thread (current-thread-os-thread))))
175     (setq *current-thread* initial-thread)
176     ;; Either *all-threads* is empty or it contains exactly one thread
177     ;; in case we are in reinit since saving core with multiple
178     ;; threads doesn't work.
179     (setq *all-threads* (list initial-thread))))
180 \f
181
182 ;;;; Aliens, low level stuff
183
184 (define-alien-routine "kill_safely"
185     integer
186   (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
187   (signal int))
188
189 #!+sb-thread
190 (progn
191   ;; FIXME it would be good to define what a thread id is or isn't
192   ;; (our current assumption is that it's a fixnum).  It so happens
193   ;; that on Linux it's a pid, but it might not be on posix thread
194   ;; implementations.
195   (define-alien-routine ("create_thread" %create-thread)
196       unsigned-long (lisp-fun-address unsigned-long))
197
198   (declaim (inline %block-deferrable-signals))
199   (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
200       void
201     (where sb!alien:unsigned-long)
202     (old sb!alien:unsigned-long))
203
204   (defun block-deferrable-signals ()
205     (%block-deferrable-signals 0 0))
206
207   #!+sb-lutex
208   (progn
209     (declaim (inline %lutex-init %lutex-wait %lutex-wake
210                      %lutex-lock %lutex-unlock))
211
212     (define-alien-routine ("lutex_init" %lutex-init)
213         int (lutex unsigned-long))
214
215     (define-alien-routine ("lutex_wait" %lutex-wait)
216         int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
217
218     (define-alien-routine ("lutex_wake" %lutex-wake)
219         int (lutex unsigned-long) (n int))
220
221     (define-alien-routine ("lutex_lock" %lutex-lock)
222         int (lutex unsigned-long))
223
224     (define-alien-routine ("lutex_trylock" %lutex-trylock)
225         int (lutex unsigned-long))
226
227     (define-alien-routine ("lutex_unlock" %lutex-unlock)
228         int (lutex unsigned-long))
229
230     (define-alien-routine ("lutex_destroy" %lutex-destroy)
231         int (lutex unsigned-long))
232
233     ;; FIXME: Defining a whole bunch of alien-type machinery just for
234     ;; passing primitive lutex objects directly to foreign functions
235     ;; doesn't seem like fun right now. So instead we just manually
236     ;; pin the lutex, get its address, and let the callee untag it.
237     (defmacro with-lutex-address ((name lutex) &body body)
238       `(let ((,name ,lutex))
239          (with-pinned-objects (,name)
240            (let ((,name (get-lisp-obj-address ,name)))
241              ,@body))))
242
243     (defun make-lutex ()
244       (/show0 "Entering MAKE-LUTEX")
245       ;; Suppress GC until the lutex has been properly registered with
246       ;; the GC.
247       (without-gcing
248         (let ((lutex (sb!vm::%make-lutex)))
249           (/show0 "LUTEX=..")
250           (/hexstr lutex)
251           (with-lutex-address (lutex lutex)
252             (%lutex-init lutex))
253           lutex))))
254
255   #!-sb-lutex
256   (progn
257     (declaim (inline futex-wait %futex-wait futex-wake))
258
259     (define-alien-routine ("futex_wait" %futex-wait)
260         int (word unsigned-long) (old-value unsigned-long)
261         (to-sec long) (to-usec unsigned-long))
262
263     (defun futex-wait (word old to-sec to-usec)
264       (with-interrupts
265         (%futex-wait word old to-sec to-usec)))
266
267     (define-alien-routine "futex_wake"
268         int (word unsigned-long) (n unsigned-long))))
269
270 ;;; used by debug-int.lisp to access interrupt contexts
271 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
272 #!-sb-thread
273 (defun sb!vm::current-thread-offset-sap (n)
274   (declare (type (unsigned-byte 27) n))
275   (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
276                (* n sb!vm:n-word-bytes)))
277
278 #!+sb-thread
279 (defun sb!vm::current-thread-offset-sap (n)
280   (declare (type (unsigned-byte 27) n))
281   (sb!vm::current-thread-offset-sap n))
282 \f
283
284 ;;;; Spinlocks
285
286 (declaim (inline get-spinlock release-spinlock))
287
288 ;;; Should always be called with interrupts disabled.
289 (defun get-spinlock (spinlock)
290   (declare (optimize (speed 3) (safety 0)))
291   (let* ((new *current-thread*)
292          (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
293     (when old
294       (when (eq old new)
295         (error "Recursive lock attempt on ~S." spinlock))
296       #!+sb-thread
297       (flet ((cas ()
298                (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
299                    (thread-yield)
300                    (return-from get-spinlock t))))
301         (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
302             ;; If interrupts are disabled, but we are allowed to
303             ;; enabled them, check for pending interrupts every once
304             ;; in a while. %CHECK-INTERRUPTS is taking shortcuts, make
305             ;; sure that deferrables are unblocked by doing an empty
306             ;; WITH-INTERRUPTS once.
307             (progn
308               (with-interrupts)
309               (loop
310                (loop repeat 128 do (cas)) ; 128 is arbitrary here
311                (sb!unix::%check-interrupts)))
312             (loop (cas)))))
313     t))
314
315 (defun release-spinlock (spinlock)
316   (declare (optimize (speed 3) (safety 0)))
317   ;; On x86 and x86-64 we can get away with no memory barriers, (see
318   ;; Linux kernel mailing list "spin_unlock optimization(i386)"
319   ;; thread, summary at
320   ;; http://kt.iserv.nl/kernel-traffic/kt19991220_47.html#1.
321   ;;
322   ;; If the compiler may reorder this with other instructions, insert
323   ;; compiler barrier here.
324   ;;
325   ;; FIXME: this does not work on SMP Pentium Pro and OOSTORE systems,
326   ;; neither on most non-x86 architectures (but we don't have threads
327   ;; on those).
328   (setf (spinlock-value spinlock) nil))
329 \f
330
331 ;;;; Mutexes
332
333 #!+sb-doc
334 (setf (fdocumentation 'make-mutex 'function)
335       "Create a mutex."
336       (fdocumentation 'mutex-name 'function)
337       "The name of the mutex. Setfable.")
338
339 #!+(and sb-thread (not sb-lutex))
340 (progn
341   (define-structure-slot-addressor mutex-state-address
342       :structure mutex
343       :slot state)
344   ;; Important: current code assumes these are fixnums or other
345   ;; lisp objects that don't need pinning.
346   (defconstant +lock-free+ 0)
347   (defconstant +lock-taken+ 1)
348   (defconstant +lock-contested+ 2))
349
350 (defun mutex-owner (mutex)
351   "Current owner of the mutex, NIL if the mutex is free. Naturally,
352 this is racy by design (another thread may acquire the mutex after
353 this function returns), it is intended for informative purposes. For
354 testing whether the current thread is holding a mutex see
355 HOLDING-MUTEX-P."
356   ;; Make sure to get the current value.
357   (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
358
359 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
360   #!+sb-doc
361   "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
362 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
363 non-NIL and the mutex is in use, sleep until it is available.
364
365 Note: using GET-MUTEX to assign a MUTEX to another thread then the
366 current one is not recommended, and liable to be deprecated.
367
368 GET-MUTEX is not interrupt safe. The correct way to call it is:
369
370  (WITHOUT-INTERRUPTS
371    ...
372    (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
373    ...)
374
375 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
376 call while the mutex is in an inconsistent state while
377 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
378
379 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
380 directly."
381   (declare (type mutex mutex) (optimize (speed 3))
382            #!-sb-thread (ignore waitp))
383   (unless new-owner
384     (setq new-owner *current-thread*))
385   (let ((old (mutex-%owner mutex)))
386     (when (eq new-owner old)
387       (error "Recursive lock attempt ~S." mutex))
388     #!-sb-thread
389     (when old
390       (error "Strange deadlock on ~S in an unithreaded build?" mutex)))
391   #!-sb-thread
392   (setf (mutex-%owner mutex) new-owner)
393   #!+sb-thread
394   (progn
395     ;; FIXME: Lutexes do not currently support deadlines, as at least
396     ;; on Darwin pthread_foo_timedbar functions are not supported:
397     ;; this means that we probably need to use the Carbon multiprocessing
398     ;; functions on Darwin.
399     ;;
400     ;; FIXME: This is definitely not interrupt safe: what happens if
401     ;; we get hit (1) during the lutex calls (ok, they may be safe,
402     ;; but has that been checked?) (2) after the lutex call, but
403     ;; before setting the mutex owner.
404     #!+sb-lutex
405     (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
406                    (if waitp
407                        (with-interrupts (%lutex-lock lutex))
408                        (%lutex-trylock lutex))))
409       (setf (mutex-%owner mutex) new-owner)
410       t)
411     #!-sb-lutex
412     ;; This is a direct translation of the Mutex 2 algorithm from
413     ;; "Futexes are Tricky" by Ulrich Drepper.
414     (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
415                                         +lock-free+
416                                         +lock-taken+)))
417       (unless (or (eql +lock-free+ old) (not waitp))
418         (tagbody
419          :retry
420            (when (or (eql +lock-contested+ old)
421                      (not (eql +lock-free+
422                                (sb!ext:compare-and-swap (mutex-state mutex)
423                                                         +lock-taken+
424                                                         +lock-contested+))))
425              ;; Wait on the contested lock.
426              (loop
427               (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
428                 (case (with-pinned-objects (mutex)
429                         (futex-wait (mutex-state-address mutex)
430                                     (get-lisp-obj-address +lock-contested+)
431                                     (or to-sec -1)
432                                     (or to-usec 0)))
433                   ((1) (signal-deadline))
434                   ((2))
435                   (otherwise (return))))))
436            (setf old (sb!ext:compare-and-swap (mutex-state mutex)
437                                               +lock-free+
438                                               +lock-contested+))
439            ;; Did we get it?
440            (unless (eql +lock-free+ old)
441              (go :retry))))
442       (cond ((eql +lock-free+ old)
443              (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
444                                                   nil new-owner)))
445                (when prev
446                  (bug "Old owner in free mutex: ~S" prev))
447                t))
448             (waitp
449              (bug "Failed to acquire lock with WAITP."))))))
450
451 (defun release-mutex (mutex &key (if-not-owner :punt))
452   #!+sb-doc
453   "Release MUTEX by setting it to NIL. Wake up threads waiting for
454 this mutex.
455
456 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
457 around calls to it.
458
459 If the current thread is not the owner of the mutex then it silently
460 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
461 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
462 IF-NOT-OWNER is :FORCE)."
463   (declare (type mutex mutex))
464   ;; Order matters: set owner to NIL before releasing state.
465   (let* ((self *current-thread*)
466          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
467     (unless (eql self old-owner)
468       (ecase if-not-owner
469         ((:punt) (return-from release-mutex nil))
470         ((:warn)
471          (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
472         ((:force))))
473     #!+sb-thread
474     (when old-owner
475       (setf (mutex-%owner mutex) nil)
476       #!+sb-lutex
477       (with-lutex-address (lutex (mutex-lutex mutex))
478         (%lutex-unlock lutex))
479       #!-sb-lutex
480       ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
481       ;; unsigned-byte type this can be used:
482       ;;
483       ;;     (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
484       ;;       (unless (eql old +lock-free+)
485       ;;         (setf (mutex-state mutex) +lock-free+)
486       ;;         (with-pinned-objects (mutex)
487       ;;           (futex-wake (mutex-state-address mutex) 1))))
488       (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
489                                           +lock-taken+ +lock-free+)))
490         (when (eql old +lock-contested+)
491           (sb!ext:compare-and-swap (mutex-state mutex)
492                                    +lock-contested+ +lock-free+)
493           (with-pinned-objects (mutex)
494             (futex-wake (mutex-state-address mutex) 1))))
495       nil)))
496 \f
497
498 ;;;; Waitqueues/condition variables
499
500 (defstruct (waitqueue (:constructor %make-waitqueue))
501   #!+sb-doc
502   "Waitqueue type."
503   (name nil :type (or null simple-string))
504   #!+(and sb-lutex sb-thread)
505   (lutex (make-lutex))
506   #!-sb-lutex
507   (data nil))
508
509 (defun make-waitqueue (&key name)
510   #!+sb-doc
511   "Create a waitqueue."
512   (%make-waitqueue :name name))
513
514 #!+sb-doc
515 (setf (fdocumentation 'waitqueue-name 'function)
516       "The name of the waitqueue. Setfable.")
517
518 #!+(and sb-thread (not sb-lutex))
519 (define-structure-slot-addressor waitqueue-data-address
520     :structure waitqueue
521     :slot data)
522
523 (defun condition-wait (queue mutex)
524   #!+sb-doc
525   "Atomically release MUTEX and enqueue ourselves on QUEUE.  Another
526 thread may subsequently notify us using CONDITION-NOTIFY, at which
527 time we reacquire MUTEX and return to the caller.
528
529 Note that if CONDITION-WAIT unwinds (due to eg. a timeout) instead of
530 returning normally, it may do so without holding the mutex."
531   #!-sb-thread (declare (ignore queue))
532   (assert mutex)
533   #!-sb-thread (error "Not supported in unithread builds.")
534   #!+sb-thread
535   (let ((me *current-thread*))
536     (assert (eq me (mutex-%owner mutex)))
537     (/show0 "CONDITION-WAITing")
538     #!+sb-lutex
539     ;; Need to disable interrupts so that we don't miss setting the
540     ;; owner on our way out. (pthread_cond_wait handles the actual
541     ;; re-acquisition.)
542     (without-interrupts
543       (unwind-protect
544            (progn
545              (setf (mutex-%owner mutex) nil)
546              (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
547                (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
548                  (with-local-interrupts
549                    (%lutex-wait queue-lutex-address mutex-lutex-address)))))
550         (setf (mutex-%owner mutex) me)))
551     #!-sb-lutex
552     ;; Need to disable interrupts so that we don't miss grabbing the
553     ;; mutex on our way out.
554     (without-interrupts
555       (let ((me nil))
556         ;; This setf becomes visible to other CPUS due to the usual
557         ;; memory barrier semantics of lock acquire/release. This must
558         ;; not be moved into the loop else wakeups may be lost upon
559         ;; continuing after a deadline or EINTR.
560         (setf (waitqueue-data queue) me)
561         (loop
562          (multiple-value-bind (to-sec to-usec)
563              (allow-with-interrupts (decode-timeout nil))
564            (case (unwind-protect
565                       (with-pinned-objects (queue me)
566                         ;; RELEASE-MUTEX is purposefully as close to
567                         ;; FUTEX-WAIT as possible to reduce the size
568                         ;; of the window where WAITQUEUE-DATA may be
569                         ;; set by a notifier.
570                         (release-mutex mutex)
571                         ;; Now we go to sleep using futex-wait. If
572                         ;; anyone else manages to grab MUTEX and call
573                         ;; CONDITION-NOTIFY during this comment, it
574                         ;; will change queue->data, and so futex-wait
575                         ;; returns immediately instead of sleeping.
576                         ;; Ergo, no lost wakeup. We may get spurious
577                         ;; wakeups, but that's ok.
578                         (allow-with-interrupts
579                           (futex-wait (waitqueue-data-address queue)
580                                       (get-lisp-obj-address me)
581                                       ;; our way of saying "no
582                                       ;; timeout":
583                                       (or to-sec -1)
584                                       (or to-usec 0))))
585                    ;; If we are interrupted while waiting, we should
586                    ;; do these things before returning. Ideally, in
587                    ;; the case of an unhandled signal, we should do
588                    ;; them before entering the debugger, but this is
589                    ;; better than nothing.
590                    (allow-with-interrupts (get-mutex mutex)))
591              ;; ETIMEDOUT; we know it was a timeout, yet we cannot
592              ;; signal a deadline unconditionally here because the
593              ;; call to GET-MUTEX may already have signaled it.
594              ((1))
595              ;; EINTR
596              ((2))
597              ;; EWOULDBLOCK, -1 here, is the possible spurious wakeup
598              ;; case. 0 is the normal wakeup.
599              (otherwise (return)))))))))
600
601 (defun condition-notify (queue &optional (n 1))
602   #!+sb-doc
603   "Notify N threads waiting on QUEUE. The same mutex that is used in
604 the corresponding CONDITION-WAIT must be held by this thread during
605 this call."
606   #!-sb-thread (declare (ignore queue n))
607   #!-sb-thread (error "Not supported in unithread builds.")
608   #!+sb-thread
609   (declare (type (and fixnum (integer 1)) n))
610   (/show0 "Entering CONDITION-NOTIFY")
611   #!+sb-thread
612   (progn
613     #!+sb-lutex
614     (with-lutex-address (lutex (waitqueue-lutex queue))
615       (%lutex-wake lutex n))
616     ;; no problem if >1 thread notifies during the comment in
617     ;; condition-wait: as long as the value in queue-data isn't the
618     ;; waiting thread's id, it matters not what it is
619     ;; XXX we should do something to ensure that the result of this setf
620     ;; is visible to all CPUs
621     #!-sb-lutex
622     (let ((me *current-thread*))
623       (progn
624         (setf (waitqueue-data queue) me)
625         (with-pinned-objects (queue)
626           (futex-wake (waitqueue-data-address queue) n))))))
627
628 (defun condition-broadcast (queue)
629   #!+sb-doc
630   "Notify all threads waiting on QUEUE."
631   (condition-notify queue
632                     ;; On a 64-bit platform truncating M-P-F to an int
633                     ;; results in -1, which wakes up only one thread.
634                     (ldb (byte 29 0)
635                          most-positive-fixnum)))
636 \f
637
638 ;;;; Semaphores
639
640 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
641   #!+sb-doc
642   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
643 should be considered an implementation detail, and may change in the
644 future."
645   (name nil :type (or null simple-string))
646   (%count 0 :type (integer 0))
647   (waitcount 0 :type (integer 0))
648   (mutex (make-mutex))
649   (queue (make-waitqueue)))
650
651 (setf (fdocumentation 'semaphore-name 'function)
652       "The name of the semaphore INSTANCE. Setfable.")
653
654 (declaim (inline semaphore-count))
655 (defun semaphore-count (instance)
656   "Returns the current count of the semaphore INSTANCE."
657   (semaphore-%count instance))
658
659 (defun make-semaphore (&key name (count 0))
660   #!+sb-doc
661   "Create a semaphore with the supplied COUNT and NAME."
662   (%make-semaphore name count))
663
664 (defun wait-on-semaphore (semaphore)
665   #!+sb-doc
666   "Decrement the count of SEMAPHORE if the count would not be
667 negative. Else blocks until the semaphore can be decremented."
668   ;; A more direct implementation based directly on futexes should be
669   ;; possible.
670   ;;
671   ;; We need to disable interrupts so that we don't forget to
672   ;; decrement the waitcount (which would happen if an asynch
673   ;; interrupt should catch us on our way out from the loop.)
674   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
675     ;; Quick check: is it positive? If not, enter the wait loop.
676     (let ((count (semaphore-%count semaphore)))
677       (if (plusp count)
678           (setf (semaphore-%count semaphore) (1- count))
679           (unwind-protect
680                (progn
681                  ;; Need to use ATOMIC-INCF despite the lock, because on our
682                  ;; way out from here we might not be locked anymore -- so
683                  ;; another thread might be tweaking this in parallel using
684                  ;; ATOMIC-DECF.
685                  (atomic-incf (semaphore-waitcount semaphore))
686                  (loop until (plusp (setf count (semaphore-%count semaphore)))
687                        do (condition-wait (semaphore-queue semaphore)
688                                           (semaphore-mutex semaphore)))
689                  (setf (semaphore-%count semaphore) (1- count)))
690             ;; Need to use ATOMIC-DECF instead of DECF, as CONDITION-WAIT
691             ;; may unwind without the lock being held due to timeouts.
692             (atomic-decf (semaphore-waitcount semaphore)))))))
693
694 (defun try-semaphore (semaphore &optional (n 1))
695   #!+sb-doc
696   "Try to decrement the count of SEMAPHORE by N. If the count were to
697 become negative, punt and return NIL, otherwise return true."
698   (declare (type (integer 1) n))
699   (with-mutex ((semaphore-mutex semaphore))
700     (let ((new-count (- (semaphore-%count semaphore) n)))
701       (when (not (minusp new-count))
702         (setf (semaphore-%count semaphore) new-count)))))
703
704 (defun signal-semaphore (semaphore &optional (n 1))
705   #!+sb-doc
706   "Increment the count of SEMAPHORE by N. If there are threads waiting
707 on this semaphore, then N of them is woken up."
708   (declare (type (integer 1) n))
709   ;; Need to disable interrupts so that we don't lose a wakeup after
710   ;; we have incremented the count.
711   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
712     (let ((waitcount (semaphore-waitcount semaphore))
713           (count (incf (semaphore-%count semaphore) n)))
714       (when (plusp waitcount)
715         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
716 \f
717
718 ;;;; Job control, independent listeners
719
720 (defstruct session
721   (lock (make-mutex :name "session lock"))
722   (threads nil)
723   (interactive-threads nil)
724   (interactive-threads-queue (make-waitqueue)))
725
726 (defvar *session* nil)
727
728 ;;; The debugger itself tries to acquire the session lock, don't let
729 ;;; funny situations (like getting a sigint while holding the session
730 ;;; lock) occur. At the same time we need to allow interrupts while
731 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
732 ;;; be interruptible.
733 ;;;
734 ;;; Take care: we sometimes need to obtain the session lock while
735 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
736 ;;; _after_ getting a session lock! (Deadlock risk.)
737 ;;;
738 ;;; FIXME: It would be good to have ordered locks to ensure invariants
739 ;;; like the above.
740 (defmacro with-session-lock ((session) &body body)
741   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
742      ,@body))
743
744 (defun new-session ()
745   (make-session :threads (list *current-thread*)
746                 :interactive-threads (list *current-thread*)))
747
748 (defun init-job-control ()
749   (/show0 "Entering INIT-JOB-CONTROL")
750   (setf *session* (new-session))
751   (/show0 "Exiting INIT-JOB-CONTROL"))
752
753 (defun %delete-thread-from-session (thread session)
754   (with-session-lock (session)
755     (setf (session-threads session)
756           (delete thread (session-threads session))
757           (session-interactive-threads session)
758           (delete thread (session-interactive-threads session)))))
759
760 (defun call-with-new-session (fn)
761   (%delete-thread-from-session *current-thread* *session*)
762   (let ((*session* (new-session)))
763     (funcall fn)))
764
765 (defmacro with-new-session (args &body forms)
766   (declare (ignore args))               ;for extensibility
767   (sb!int:with-unique-names (fb-name)
768     `(labels ((,fb-name () ,@forms))
769       (call-with-new-session (function ,fb-name)))))
770
771 ;;; Remove thread from its session, if it has one.
772 #!+sb-thread
773 (defun handle-thread-exit (thread)
774   (/show0 "HANDLING THREAD EXIT")
775   ;; Lisp-side cleanup
776   (with-all-threads-lock
777     (setf (thread-%alive-p thread) nil)
778     (setf (thread-os-thread thread) nil)
779     (setq *all-threads* (delete thread *all-threads*))
780     (when *session*
781       (%delete-thread-from-session thread *session*)))
782   #!+sb-lutex
783   (without-gcing
784     (/show0 "FREEING MUTEX LUTEX")
785     (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
786       (%lutex-destroy lutex))))
787
788 (defun terminate-session ()
789   #!+sb-doc
790   "Kill all threads in session except for this one.  Does nothing if current
791 thread is not the foreground thread."
792   ;; FIXME: threads created in other threads may escape termination
793   (let ((to-kill
794          (with-session-lock (*session*)
795            (and (eq *current-thread*
796                     (car (session-interactive-threads *session*)))
797                 (session-threads *session*)))))
798     ;; do the kill after dropping the mutex; unwind forms in dying
799     ;; threads may want to do session things
800     (dolist (thread to-kill)
801       (unless (eq thread *current-thread*)
802         ;; terminate the thread but don't be surprised if it has
803         ;; exited in the meantime
804         (handler-case (terminate-thread thread)
805           (interrupt-thread-error ()))))))
806
807 ;;; called from top of invoke-debugger
808 (defun debugger-wait-until-foreground-thread (stream)
809   "Returns T if thread had been running in background, NIL if it was
810 interactive."
811   (declare (ignore stream))
812   #!-sb-thread nil
813   #!+sb-thread
814   (prog1
815       (with-session-lock (*session*)
816         (not (member *current-thread*
817                      (session-interactive-threads *session*))))
818     (get-foreground)))
819
820 (defun get-foreground ()
821   #!-sb-thread t
822   #!+sb-thread
823   (let ((was-foreground t))
824     (loop
825      (/show0 "Looping in GET-FOREGROUND")
826      (with-session-lock (*session*)
827        (let ((int-t (session-interactive-threads *session*)))
828          (when (eq (car int-t) *current-thread*)
829            (unless was-foreground
830              (format *query-io* "Resuming thread ~A~%" *current-thread*))
831            (return-from get-foreground t))
832          (setf was-foreground nil)
833          (unless (member *current-thread* int-t)
834            (setf (cdr (last int-t))
835                  (list *current-thread*)))
836          (condition-wait
837           (session-interactive-threads-queue *session*)
838           (session-lock *session*)))))))
839
840 (defun release-foreground (&optional next)
841   #!+sb-doc
842   "Background this thread.  If NEXT is supplied, arrange for it to
843 have the foreground next."
844   #!-sb-thread (declare (ignore next))
845   #!-sb-thread nil
846   #!+sb-thread
847   (with-session-lock (*session*)
848     (when (rest (session-interactive-threads *session*))
849       (setf (session-interactive-threads *session*)
850             (delete *current-thread* (session-interactive-threads *session*))))
851     (when next
852       (setf (session-interactive-threads *session*)
853             (list* next
854                    (delete next (session-interactive-threads *session*)))))
855     (condition-broadcast (session-interactive-threads-queue *session*))))
856
857 (defun foreground-thread ()
858   (car (session-interactive-threads *session*)))
859
860 (defun make-listener-thread (tty-name)
861   (assert (probe-file tty-name))
862   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
863          (out (sb!unix:unix-dup in))
864          (err (sb!unix:unix-dup in)))
865     (labels ((thread-repl ()
866                (sb!unix::unix-setsid)
867                (let* ((sb!impl::*stdin*
868                        (make-fd-stream in :input t :buffering :line
869                                        :dual-channel-p t))
870                       (sb!impl::*stdout*
871                        (make-fd-stream out :output t :buffering :line
872                                               :dual-channel-p t))
873                       (sb!impl::*stderr*
874                        (make-fd-stream err :output t :buffering :line
875                                               :dual-channel-p t))
876                       (sb!impl::*tty*
877                        (make-fd-stream err :input t :output t
878                                               :buffering :line
879                                               :dual-channel-p t))
880                       (sb!impl::*descriptor-handlers* nil))
881                  (with-new-session ()
882                    (unwind-protect
883                         (sb!impl::toplevel-repl nil)
884                      (sb!int:flush-standard-output-streams))))))
885       (make-thread #'thread-repl))))
886 \f
887
888 ;;;; The beef
889
890 (defun make-thread (function &key name)
891   #!+sb-doc
892   "Create a new thread of NAME that runs FUNCTION. When the function
893 returns the thread exits. The return values of FUNCTION are kept
894 around and can be retrieved by JOIN-THREAD."
895   #!-sb-thread (declare (ignore function name))
896   #!-sb-thread (error "Not supported in unithread builds.")
897   #!+sb-thread
898   (let* ((thread (%make-thread :name name))
899          (setup-sem (make-semaphore :name "Thread setup semaphore"))
900          (real-function (coerce function 'function))
901          (initial-function
902           (named-lambda initial-thread-function ()
903             ;; In time we'll move some of the binding presently done in C
904             ;; here too.
905             ;;
906             ;; KLUDGE: Here we have a magic list of variables that are
907             ;; not thread-safe for one reason or another.  As people
908             ;; report problems with the thread safety of certain
909             ;; variables, (e.g. "*print-case* in multiple threads
910             ;; broken", sbcl-devel 2006-07-14), we add a few more
911             ;; bindings here.  The Right Thing is probably some variant
912             ;; of Allegro's *cl-default-special-bindings*, as that is at
913             ;; least accessible to users to secure their own libraries.
914             ;;   --njf, 2006-07-15
915             ;;
916             ;; As it is, this lambda must not cons until we are ready
917             ;; to run GC. Be very careful.
918             (let* ((*current-thread* thread)
919                    (*restart-clusters* nil)
920                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
921                    (*condition-restarts* nil)
922                    (sb!impl::*deadline* nil)
923                    (sb!impl::*deadline-seconds* nil)
924                    (sb!impl::*step-out* nil)
925                    ;; internal printer variables
926                    (sb!impl::*previous-case* nil)
927                    (sb!impl::*previous-readtable-case* nil)
928                    (sb!impl::*internal-symbol-output-fun* nil)
929                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
930               ;; Binding from C
931               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
932               (setf (thread-os-thread thread) (current-thread-os-thread))
933               (with-mutex ((thread-result-lock thread))
934                 (with-all-threads-lock
935                   (push thread *all-threads*))
936                 (with-session-lock (*session*)
937                   (push thread (session-threads *session*)))
938                 (setf (thread-%alive-p thread) t)
939                 (signal-semaphore setup-sem)
940                 ;; can't use handling-end-of-the-world, because that flushes
941                 ;; output streams, and we don't necessarily have any (or we
942                 ;; could be sharing them)
943                 (catch 'sb!impl::toplevel-catcher
944                   (catch 'sb!impl::%end-of-the-world
945                     (with-simple-restart
946                         (terminate-thread
947                          (format nil
948                                  "~~@<Terminate this thread (~A)~~@:>"
949                                  *current-thread*))
950                       (without-interrupts
951                         (unwind-protect
952                              (with-local-interrupts
953                                ;; Now that most things have a chance
954                                ;; to work properly without messing up
955                                ;; other threads, it's time to enable
956                                ;; signals.
957                                (sb!unix::unblock-deferrable-signals)
958                                (setf (thread-result thread)
959                                      (cons t
960                                            (multiple-value-list
961                                             (funcall real-function))))
962                                ;; Try to block deferrables. An
963                                ;; interrupt may unwind it, but for a
964                                ;; normal exit it prevents interrupt
965                                ;; loss.
966                                (block-deferrable-signals))
967                           ;; We're going down, can't handle interrupts
968                           ;; sanely anymore. GC remains enabled.
969                           (block-deferrable-signals)
970                           ;; We don't want to run interrupts in a dead
971                           ;; thread when we leave WITHOUT-INTERRUPTS.
972                           ;; This potentially causes important
973                           ;; interupts to be lost: SIGINT comes to
974                           ;; mind.
975                           (setq *interrupt-pending* nil)
976                           (handle-thread-exit thread))))))))
977             (values))))
978     ;; If the starting thread is stopped for gc before it signals the
979     ;; semaphore then we'd be stuck.
980     (assert (not *gc-inhibit*))
981     ;; Keep INITIAL-FUNCTION pinned until the child thread is
982     ;; initialized properly. Wrap the whole thing in
983     ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
984     ;; thread.
985     (without-interrupts
986       (with-pinned-objects (initial-function)
987         (let ((os-thread
988                (%create-thread
989                 (get-lisp-obj-address initial-function))))
990           (when (zerop os-thread)
991             (error "Can't create a new thread"))
992           (wait-on-semaphore setup-sem)
993           thread)))))
994
995 (defun join-thread (thread &key (default nil defaultp))
996   #!+sb-doc
997   "Suspend current thread until THREAD exits. Returns the result
998 values of the thread function. If the thread does not exit normally,
999 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
1000   (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
1001     (cond ((car (thread-result thread))
1002            (return-from join-thread
1003              (values-list (cdr (thread-result thread)))))
1004           (defaultp
1005            (return-from join-thread default))))
1006   (error 'join-thread-error :thread thread))
1007
1008 (defun destroy-thread (thread)
1009   #!+sb-doc
1010   "Deprecated. Same as TERMINATE-THREAD."
1011   (terminate-thread thread))
1012
1013 (defmacro with-interruptions-lock ((thread) &body body)
1014   `(with-system-mutex ((thread-interruptions-lock ,thread))
1015      ,@body))
1016
1017 ;;; Called from the signal handler.
1018 #!-win32
1019 (defun run-interruption ()
1020   (let ((interruption (with-interruptions-lock (*current-thread*)
1021                         (pop (thread-interruptions *current-thread*)))))
1022     ;; If there is more to do, then resignal and let the normal
1023     ;; interrupt deferral mechanism take care of the rest. From the
1024     ;; OS's point of view the signal we are in the handler for is no
1025     ;; longer pending, so the signal will not be lost.
1026     (when (thread-interruptions *current-thread*)
1027       (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1028     (when interruption
1029       (funcall interruption))))
1030
1031 (defun interrupt-thread (thread function)
1032   #!+sb-doc
1033   "Interrupt the live THREAD and make it run FUNCTION. A moderate
1034 degree of care is expected for use of INTERRUPT-THREAD, due to its
1035 nature: if you interrupt a thread that was holding important locks
1036 then do something that turns out to need those locks, you probably
1037 won't like the effect. FUNCTION runs with interrupts disabled, but
1038 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1039 enable interrupts (GET-MUTEX when contended, for instance) so the
1040 first thing to do is usually a WITH-INTERRUPTS or a
1041 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1042 run in same the order they were sent."
1043   #!+win32
1044   (declare (ignore thread))
1045   #!+win32
1046   (with-interrupt-bindings
1047     (with-interrupts (funcall function)))
1048   #!-win32
1049   (let ((os-thread (thread-os-thread thread)))
1050     (cond ((not os-thread)
1051            (error 'interrupt-thread-error :thread thread))
1052           (t
1053            (with-interruptions-lock (thread)
1054              ;; Append to the end of the interruptions queue. It's
1055              ;; O(N), but it does not hurt to slow interruptors down a
1056              ;; bit when the queue gets long.
1057              (setf (thread-interruptions thread)
1058                    (append (thread-interruptions thread)
1059                            (list (lambda ()
1060                                    (without-interrupts
1061                                      (allow-with-interrupts
1062                                        (funcall function))))))))
1063            (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1064              (error 'interrupt-thread-error :thread thread))))))
1065
1066 (defun terminate-thread (thread)
1067   #!+sb-doc
1068   "Terminate the thread identified by THREAD, by causing it to run
1069 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1070   (interrupt-thread thread 'sb!ext:quit))
1071
1072 (define-alien-routine "thread_yield" int)
1073
1074 #!+sb-doc
1075 (setf (fdocumentation 'thread-yield 'function)
1076       "Yield the processor to other threads.")
1077
1078 ;;; internal use only.  If you think you need to use these, either you
1079 ;;; are an SBCL developer, are doing something that you should discuss
1080 ;;; with an SBCL developer first, or are doing something that you
1081 ;;; should probably discuss with a professional psychiatrist first
1082 #!+sb-thread
1083 (progn
1084   (defun %thread-sap (thread)
1085     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1086           (target (thread-os-thread thread)))
1087       (loop
1088         (when (sap= thread-sap (int-sap 0)) (return nil))
1089         (let ((os-thread (sap-ref-word thread-sap
1090                                        (* sb!vm:n-word-bytes
1091                                           sb!vm::thread-os-thread-slot))))
1092           (when (= os-thread target) (return thread-sap))
1093           (setf thread-sap
1094                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1095                                            sb!vm::thread-next-slot)))))))
1096
1097   (defun %symbol-value-in-thread (symbol thread)
1098     ;; Prevent the thread from dying completely while we look for the TLS
1099     ;; area...
1100     (with-all-threads-lock
1101       (loop
1102         (if (thread-alive-p thread)
1103             (let* ((epoch sb!kernel::*gc-epoch*)
1104                    (offset (* sb!vm:n-word-bytes
1105                               (sb!vm::symbol-tls-index symbol)))
1106                    (tl-val (sap-ref-word (%thread-sap thread) offset)))
1107               (cond ((zerop offset)
1108                      (return (values nil :no-tls-value)))
1109                     ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1110                          (eql tl-val sb!vm:unbound-marker-widetag))
1111                      (return (values nil :unbound-in-thread)))
1112                     (t
1113                      (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
1114                        ;; The value we constructed may be invalid if a GC has
1115                        ;; occurred. That is harmless, though, since OBJ is
1116                        ;; either in a register or on stack, and we are
1117                        ;; conservative on both on GENCGC -- so a bogus object
1118                        ;; is safe here as long as we don't return it. If we
1119                        ;; ever port threads to a non-conservative GC we must
1120                        ;; pin the TL-VAL address before constructing OBJ, or
1121                        ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
1122                        ;;
1123                        ;; The reason we don't just rely on TL-VAL pinning the
1124                        ;; object is that the call to MAKE-LISP-OBJ may cause
1125                        ;; bignum allocation, at which point TL-VAL might not
1126                        ;; be alive anymore -- hence the epoch check.
1127                        (when (eq epoch sb!kernel::*gc-epoch*)
1128                          (if ok
1129                              (return (values obj :ok))
1130                              (return (values obj :invalid-tls-value))))))))
1131             (return (values nil :thread-dead))))))
1132
1133   (defun %set-symbol-value-in-thread (symbol thread value)
1134     (with-pinned-objects (value)
1135       ;; Prevent the thread from dying completely while we look for the TLS
1136       ;; area...
1137       (with-all-threads-lock
1138         (if (thread-alive-p thread)
1139             (let ((offset (* sb!vm:n-word-bytes
1140                              (sb!vm::symbol-tls-index symbol))))
1141               (cond ((zerop offset)
1142                      (values nil :no-tls-value))
1143                     (t
1144                      (setf (sap-ref-word (%thread-sap thread) offset)
1145                            (get-lisp-obj-address value))
1146                      (values value :ok))))
1147             (values nil :thread-dead))))))
1148
1149 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1150   "Return the local value of SYMBOL in THREAD, and a secondary value of T
1151 on success.
1152
1153 If the value cannot be retrieved (because the thread has exited or because it
1154 has no local binding for NAME) and ERRORP is true signals an error of type
1155 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1156 NIL, and a secondary value of NIL.
1157
1158 Can also be used with SETF to change the thread-local value of SYMBOL.
1159
1160 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1161 mechanism for inter-thread communication."
1162   (declare (symbol symbol) (thread thread))
1163   #!+sb-thread
1164   (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1165     (if (eq :ok status)
1166         (values res t)
1167         (if errorp
1168             (error 'symbol-value-in-thread-error
1169                    :name symbol
1170                    :thread thread
1171                    :info (list :read status))
1172             (values nil nil))))
1173   #!-sb-thread
1174   (if (boundp symbol)
1175       (values (symbol-value symbol) t)
1176       (if errorp
1177           (error 'symbol-value-in-thread-error
1178                  :name symbol
1179                  :thread thread
1180                  :info (list :read :unbound-in-thread))
1181           (values nil nil))))
1182
1183 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1184   (declare (symbol symbol) (thread thread))
1185   #!+sb-thread
1186   (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1187     (if (eq :ok status)
1188         (values res t)
1189         (if errorp
1190             (error 'symbol-value-in-thread-error
1191                    :name symbol
1192                    :thread thread
1193                    :info (list :write status))
1194             (values nil nil))))
1195   #!-sb-thread
1196   (if (boundp symbol)
1197       (values (setf (symbol-value symbol) value) t)
1198       (if errorp
1199           (error 'symbol-value-in-thread-error
1200                  :name symbol
1201                  :thread thread
1202                  :info (list :write :unbound-in-thread))
1203           (values nil nil))))
1204
1205 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1206   (sb!vm::locked-symbol-global-value-add symbol-name delta))
1207 \f
1208
1209 ;;;; Stepping
1210
1211 (defun thread-stepping ()
1212   (make-lisp-obj
1213    (sap-ref-word (current-thread-sap)
1214                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1215
1216 (defun (setf thread-stepping) (value)
1217   (setf (sap-ref-word (current-thread-sap)
1218                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1219         (get-lisp-obj-address value)))