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