0.9.16.38:
[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 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
15 ;;; necessary because threads are only supported with the conservative
16 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
17 ;;; are treated as references.
18
19 ;;; set the doc here because in early-thread FDOCUMENTATION is not
20 ;;; available, yet
21 #!+sb-doc
22 (setf (sb!kernel:fdocumentation '*current-thread* 'variable)
23       "Bound in each thread to the thread itself.")
24
25 (defstruct (thread (:constructor %make-thread))
26   #!+sb-doc
27   "Thread type. Do not rely on threads being structs as it may change
28 in future versions."
29   name
30   %alive-p
31   os-thread
32   interruptions
33   (interruptions-lock (make-mutex :name "thread interruptions lock")))
34
35 #!+sb-doc
36 (setf (sb!kernel:fdocumentation 'thread-name 'function)
37       "The name of the thread. Setfable.")
38
39 (def!method print-object ((thread thread) stream)
40   (if (thread-name thread)
41       (print-unreadable-object (thread stream :type t :identity t)
42         (prin1 (thread-name thread) stream))
43       (print-unreadable-object (thread stream :type t :identity t)
44         ;; body is empty => there is only one space between type and
45         ;; identity
46         ))
47   thread)
48
49 (defun thread-alive-p (thread)
50   #!+sb-doc
51   "Check if THREAD is running."
52   (thread-%alive-p thread))
53
54 ;; A thread is eligible for gc iff it has finished and there are no
55 ;; more references to it. This list is supposed to keep a reference to
56 ;; all running threads.
57 (defvar *all-threads* ())
58 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
59
60 (defun list-all-threads ()
61   #!+sb-doc
62   "Return a list of the live threads."
63   (with-mutex (*all-threads-lock*)
64     (copy-list *all-threads*)))
65
66 (declaim (inline current-thread-sap))
67 (defun current-thread-sap ()
68   (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
69
70 (declaim (inline current-thread-sap-id))
71 (defun current-thread-sap-id ()
72   (sap-int
73    (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
74
75 (defun init-initial-thread ()
76   (/show0 "Entering INIT-INITIAL-THREAD")
77   (let ((initial-thread (%make-thread :name "initial thread"
78                                       :%alive-p t
79                                       :os-thread (current-thread-sap-id))))
80     (setq *current-thread* initial-thread)
81     ;; Either *all-threads* is empty or it contains exactly one thread
82     ;; in case we are in reinit since saving core with multiple
83     ;; threads doesn't work.
84     (setq *all-threads* (list initial-thread))))
85
86 ;;;;
87
88 #!+sb-thread
89 (progn
90   ;; FIXME it would be good to define what a thread id is or isn't
91   ;; (our current assumption is that it's a fixnum).  It so happens
92   ;; that on Linux it's a pid, but it might not be on posix thread
93   ;; implementations.
94   (define-alien-routine ("create_thread" %create-thread)
95       unsigned-long (lisp-fun-address unsigned-long))
96
97   (define-alien-routine "signal_interrupt_thread"
98       integer (os-thread unsigned-long))
99
100   (define-alien-routine "block_blockable_signals"
101       void)
102
103   #!+sb-lutex
104   (progn
105     (declaim (inline %lutex-init %lutex-wait %lutex-wake
106                      %lutex-lock %lutex-unlock))
107
108     (sb!alien:define-alien-routine ("lutex_init" %lutex-init)
109         int (lutex unsigned-long))
110
111     (sb!alien:define-alien-routine ("lutex_wait" %lutex-wait)
112         int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
113
114     (sb!alien:define-alien-routine ("lutex_wake" %lutex-wake)
115         int (lutex unsigned-long) (n int))
116
117     (sb!alien:define-alien-routine ("lutex_lock" %lutex-lock)
118         int (lutex unsigned-long))
119
120     (sb!alien:define-alien-routine ("lutex_unlock" %lutex-unlock)
121         int (lutex unsigned-long))
122
123     (sb!alien:define-alien-routine ("lutex_destroy" %lutex-destroy)
124         int (lutex unsigned-long))
125
126     ;; FIXME: Defining a whole bunch of alien-type machinery just for
127     ;; passing primitive lutex objects directly to foreign functions
128     ;; doesn't seem like fun right now. So instead we just manually
129     ;; pin the lutex, get its address, and let the callee untag it.
130     (defmacro with-lutex-address ((name lutex) &body body)
131       `(let ((,name ,lutex))
132          (with-pinned-objects (,name)
133            (let ((,name (sb!kernel:get-lisp-obj-address ,name)))
134              ,@body))))
135
136     (defun make-lutex ()
137       (/show0 "Entering MAKE-LUTEX")
138       ;; Suppress GC until the lutex has been properly registered with
139       ;; the GC.
140       (without-gcing
141         (let ((lutex (sb!vm::%make-lutex)))
142           (/show0 "LUTEX=..")
143           (/hexstr lutex)
144           (with-lutex-address (lutex lutex)
145             (%lutex-init lutex))
146           lutex))))
147
148   #!-sb-lutex
149   (progn
150     (declaim (inline futex-wait futex-wake))
151
152     (sb!alien:define-alien-routine "futex_wait"
153         int (word unsigned-long) (old-value unsigned-long))
154
155     (sb!alien:define-alien-routine "futex_wake"
156         int (word unsigned-long) (n unsigned-long))))
157
158 ;;; used by debug-int.lisp to access interrupt contexts
159 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
160 #!-sb-thread
161 (defun sb!vm::current-thread-offset-sap (n)
162   (declare (type (unsigned-byte 27) n))
163   (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
164                (* n sb!vm:n-word-bytes)))
165
166 #!+sb-thread
167 (defun sb!vm::current-thread-offset-sap (n)
168   (declare (type (unsigned-byte 27) n))
169   (sb!vm::current-thread-offset-sap n))
170
171 ;;;; spinlocks
172
173 (declaim (inline get-spinlock release-spinlock))
174
175 ;;; The bare 2 here and below are offsets of the slots in the struct.
176 ;;; There ought to be some better way to get these numbers
177 (defun get-spinlock (spinlock)
178   (declare (optimize (speed 3) (safety 0))
179            #!-sb-thread
180            (ignore spinlock new-value))
181   ;; %instance-set-conditional can test for 0 (which is a fixnum) and
182   ;; store any value
183   #!+sb-thread
184   (loop until
185         (eql (sb!vm::%instance-set-conditional spinlock 2 0 1) 0)))
186
187 (defun release-spinlock (spinlock)
188   (declare (optimize (speed 3) (safety 0))
189            #!-sb-thread (ignore spinlock))
190   ;; %instance-set-conditional cannot compare arbitrary objects
191   ;; meaningfully, so
192   ;; (sb!vm::%instance-set-conditional spinlock 2 our-value 0)
193   ;; does not work for bignum thread ids.
194   #!+sb-thread
195   (sb!vm::%instance-set spinlock 2 0))
196
197 (defmacro with-spinlock ((spinlock) &body body)
198   (sb!int:with-unique-names (lock)
199     `(let ((,lock ,spinlock))
200       (get-spinlock ,lock)
201       (unwind-protect
202            (progn ,@body)
203         (release-spinlock ,lock)))))
204
205 ;;;; mutexes
206
207 #!+sb-doc
208 (setf (sb!kernel:fdocumentation 'make-mutex 'function)
209       "Create a mutex."
210       (sb!kernel:fdocumentation 'mutex-name 'function)
211       "The name of the mutex. Setfable."
212       (sb!kernel:fdocumentation 'mutex-value 'function)
213       "The value of the mutex. NIL if the mutex is free. Setfable.")
214
215 #!+(and sb-thread (not sb-lutex))
216 (progn
217   (declaim (inline mutex-value-address))
218   (defun mutex-value-address (mutex)
219     (declare (optimize (speed 3)))
220     (sb!ext:truly-the
221      sb!vm:word
222      (+ (sb!kernel:get-lisp-obj-address mutex)
223         (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag)))))
224
225 (defun get-mutex (mutex &optional (new-value *current-thread*) (wait-p t))
226   #!+sb-doc
227   "Acquire MUTEX, setting it to NEW-VALUE or some suitable default
228 value if NIL.  If WAIT-P is non-NIL and the mutex is in use, sleep
229 until it is available"
230   (declare (type mutex mutex) (optimize (speed 3)))
231   (/show0 "Entering GET-MUTEX")
232   (unless new-value
233     (setq new-value *current-thread*))
234   #!-sb-thread
235   (let ((old-value (mutex-value mutex)))
236     (when (and old-value wait-p)
237       (error "In unithread mode, mutex ~S was requested with WAIT-P ~S and ~
238               new-value ~S, but has already been acquired (with value ~S)."
239              mutex wait-p new-value old-value))
240     (setf (mutex-value mutex) new-value)
241     t)
242   #!+sb-thread
243   (progn
244     (when (eql new-value (mutex-value mutex))
245       (warn "recursive lock attempt ~S~%" mutex)
246       (format *debug-io* "Thread: ~A~%" *current-thread*)
247       (sb!debug:backtrace most-positive-fixnum *debug-io*)
248       (force-output *debug-io*))
249     ;; FIXME: sb-lutex and (not wait-p)
250     #!+sb-lutex
251     (when wait-p
252       (with-lutex-address (lutex (mutex-lutex mutex))
253         (%lutex-lock lutex))
254       (setf (mutex-value mutex) new-value))
255     #!-sb-lutex
256     (let (old)
257       (loop
258          (unless
259              (setf old (sb!vm::%instance-set-conditional mutex 2 nil
260                                                          new-value))
261            (return t))
262          (unless wait-p (return nil))
263          (with-pinned-objects (mutex old)
264            (futex-wait (mutex-value-address mutex)
265                        (sb!kernel:get-lisp-obj-address old)))))))
266
267 (defun release-mutex (mutex)
268   #!+sb-doc
269   "Release MUTEX by setting it to NIL. Wake up threads waiting for
270 this mutex."
271   (declare (type mutex mutex))
272   (/show0 "Entering RELEASE-MUTEX")
273   (setf (mutex-value mutex) nil)
274   #!+sb-thread
275   (progn
276     #!+sb-lutex
277     (with-lutex-address (lutex (mutex-lutex mutex))
278       (%lutex-unlock lutex))
279     #!-sb-lutex
280     (futex-wake (mutex-value-address mutex) 1)))
281
282 ;;;; waitqueues/condition variables
283
284 (defstruct (waitqueue (:constructor %make-waitqueue))
285   #!+sb-doc
286   "Waitqueue type."
287   (name nil :type (or null simple-string))
288   #!+(and sb-lutex sb-thread)
289   (lutex (make-lutex))
290   #!-sb-lutex
291   (data nil))
292
293 (defun make-waitqueue (&key name)
294   #!+sb-doc
295   "Create a waitqueue."
296   (%make-waitqueue :name name))
297
298 #!+sb-doc
299 (setf (sb!kernel:fdocumentation 'waitqueue-name 'function)
300       "The name of the waitqueue. Setfable.")
301
302 #!+(and sb-thread (not sb-lutex))
303 (progn
304   (declaim (inline waitqueue-data-address))
305   (defun waitqueue-data-address (waitqueue)
306     (declare (optimize (speed 3)))
307     (sb!ext:truly-the
308      sb!vm:word
309      (+ (sb!kernel:get-lisp-obj-address waitqueue)
310         (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag)))))
311
312 (defun condition-wait (queue mutex)
313   #!+sb-doc
314   "Atomically release MUTEX and enqueue ourselves on QUEUE.  Another
315 thread may subsequently notify us using CONDITION-NOTIFY, at which
316 time we reacquire MUTEX and return to the caller."
317   #!-sb-thread (declare (ignore queue))
318   (assert mutex)
319   #!-sb-thread (error "Not supported in unithread builds.")
320   #!+sb-thread
321   (let ((value (mutex-value mutex)))
322     (/show0 "CONDITION-WAITing")
323     #!+sb-lutex
324     (progn
325       (setf (mutex-value mutex) nil)
326       (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
327         (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
328           (%lutex-wait queue-lutex-address mutex-lutex-address)))
329       (setf (mutex-value mutex) value))
330     #!-sb-lutex
331     (unwind-protect
332          (let ((me *current-thread*))
333            ;; XXX we should do something to ensure that the result of this setf
334            ;; is visible to all CPUs
335            (setf (waitqueue-data queue) me)
336            (release-mutex mutex)
337            ;; Now we go to sleep using futex-wait.  If anyone else
338            ;; manages to grab MUTEX and call CONDITION-NOTIFY during
339            ;; this comment, it will change queue->data, and so
340            ;; futex-wait returns immediately instead of sleeping.
341            ;; Ergo, no lost wakeup
342            (with-pinned-objects (queue me)
343              (futex-wait (waitqueue-data-address queue)
344                          (sb!kernel:get-lisp-obj-address me))))
345       ;; If we are interrupted while waiting, we should do these things
346       ;; before returning.  Ideally, in the case of an unhandled signal,
347       ;; we should do them before entering the debugger, but this is
348       ;; better than nothing.
349       (get-mutex mutex value))))
350
351 (defun condition-notify (queue &optional (n 1))
352   #!+sb-doc
353   "Notify N threads waiting on QUEUE."
354   #!-sb-thread (declare (ignore queue n))
355   #!-sb-thread (error "Not supported in unithread builds.")
356   #!+sb-thread
357   (declare (type (and fixnum (integer 1)) n))
358   (/show0 "Entering CONDITION-NOTIFY")
359   #!+sb-thread
360   (progn
361     #!+sb-lutex
362     (with-lutex-address (lutex (waitqueue-lutex queue))
363       (%lutex-wake lutex n))
364     ;; no problem if >1 thread notifies during the comment in
365     ;; condition-wait: as long as the value in queue-data isn't the
366     ;; waiting thread's id, it matters not what it is
367     ;; XXX we should do something to ensure that the result of this setf
368     ;; is visible to all CPUs
369     #!-sb-lutex
370     (let ((me *current-thread*))
371       (progn
372         (setf (waitqueue-data queue) me)
373         (with-pinned-objects (queue)
374           (futex-wake (waitqueue-data-address queue) n))))))
375
376 (defun condition-broadcast (queue)
377   #!+sb-doc
378   "Notify all threads waiting on QUEUE."
379   (condition-notify queue
380                     ;; On a 64-bit platform truncating M-P-F to an int results
381                     ;; in -1, which wakes up only one thread.
382                     (ldb (byte 29 0)
383                          most-positive-fixnum)))
384
385 ;;;; semaphores
386
387 (defstruct (semaphore (:constructor %make-semaphore))
388   #!+sb-doc
389   "Semaphore type."
390   (name nil :type (or null simple-string))
391   (count 0 :type (integer 0))
392   (mutex (make-mutex))
393   (queue (make-waitqueue)))
394
395 (defun make-semaphore (&key name (count 0))
396   #!+sb-doc
397   "Create a semaphore with the supplied COUNT."
398   (%make-semaphore :name name :count count))
399
400 (setf (sb!kernel:fdocumentation 'semaphore-name 'function)
401       "The name of the semaphore. Setfable.")
402
403 (defun wait-on-semaphore (sem)
404   #!+sb-doc
405   "Decrement the count of SEM if the count would not be negative. Else
406 block until the semaphore can be decremented."
407   ;; a more direct implementation based directly on futexes should be
408   ;; possible
409   (with-mutex ((semaphore-mutex sem))
410     (loop until (> (semaphore-count sem) 0)
411           do (condition-wait (semaphore-queue sem) (semaphore-mutex sem))
412           finally (decf (semaphore-count sem)))))
413
414 (defun signal-semaphore (sem &optional (n 1))
415   #!+sb-doc
416   "Increment the count of SEM by N. If there are threads waiting on
417 this semaphore, then N of them is woken up."
418   (declare (type (and fixnum (integer 1)) n))
419   (with-mutex ((semaphore-mutex sem))
420     (when (= n (incf (semaphore-count sem) n))
421       (condition-notify (semaphore-queue sem) n))))
422
423 ;;;; job control, independent listeners
424
425 (defstruct session
426   (lock (make-mutex :name "session lock"))
427   (threads nil)
428   (interactive-threads nil)
429   (interactive-threads-queue (make-waitqueue)))
430
431 (defvar *session* nil)
432
433 ;;; the debugger itself tries to acquire the session lock, don't let
434 ;;; funny situations (like getting a sigint while holding the session
435 ;;; lock) occur
436 (defmacro with-session-lock ((session) &body body)
437   #!-sb-thread (declare (ignore session))
438   #!-sb-thread
439   `(locally ,@body)
440   #!+sb-thread
441   `(without-interrupts
442      (with-mutex ((session-lock ,session))
443        ,@body)))
444
445 (defun new-session ()
446   (make-session :threads (list *current-thread*)
447                 :interactive-threads (list *current-thread*)))
448
449 (defun init-job-control ()
450   (/show0 "Entering INIT-JOB-CONTROL")
451   (setf *session* (new-session))
452   (/show0 "Exiting INIT-JOB-CONTROL"))
453
454 (defun %delete-thread-from-session (thread session)
455   (with-session-lock (session)
456     (setf (session-threads session)
457           (delete thread (session-threads session))
458           (session-interactive-threads session)
459           (delete thread (session-interactive-threads session)))))
460
461 (defun call-with-new-session (fn)
462   (%delete-thread-from-session *current-thread* *session*)
463   (let ((*session* (new-session)))
464     (funcall fn)))
465
466 (defmacro with-new-session (args &body forms)
467   (declare (ignore args))               ;for extensibility
468   (sb!int:with-unique-names (fb-name)
469     `(labels ((,fb-name () ,@forms))
470       (call-with-new-session (function ,fb-name)))))
471
472 ;;; Remove thread from its session, if it has one.
473 #!+sb-thread
474 (defun handle-thread-exit (thread)
475   (with-mutex (*all-threads-lock*)
476     (/show0 "HANDLING THREAD EXIT")
477     #!+sb-lutex
478     (when (thread-interruptions-lock thread)
479       (/show0 "FREEING MUTEX LUTEX")
480       (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
481         (%lutex-destroy lutex)))
482     (setq *all-threads* (delete thread *all-threads*)))
483   (when *session*
484     (%delete-thread-from-session thread *session*)))
485
486 (defun terminate-session ()
487   #!+sb-doc
488   "Kill all threads in session except for this one.  Does nothing if current
489 thread is not the foreground thread."
490   ;; FIXME: threads created in other threads may escape termination
491   (let ((to-kill
492          (with-session-lock (*session*)
493            (and (eq *current-thread*
494                     (car (session-interactive-threads *session*)))
495                 (session-threads *session*)))))
496     ;; do the kill after dropping the mutex; unwind forms in dying
497     ;; threads may want to do session things
498     (dolist (thread to-kill)
499       (unless (eq thread *current-thread*)
500         ;; terminate the thread but don't be surprised if it has
501         ;; exited in the meantime
502         (handler-case (terminate-thread thread)
503           (interrupt-thread-error ()))))))
504
505 ;;; called from top of invoke-debugger
506 (defun debugger-wait-until-foreground-thread (stream)
507   "Returns T if thread had been running in background, NIL if it was
508 interactive."
509   (declare (ignore stream))
510   #!-sb-thread nil
511   #!+sb-thread
512   (prog1
513       (with-session-lock (*session*)
514         (not (member *current-thread*
515                      (session-interactive-threads *session*))))
516     (get-foreground)))
517
518 (defun get-foreground ()
519   #!-sb-thread t
520   #!+sb-thread
521   (let ((was-foreground t))
522     (loop
523      (/show0 "Looping in GET-FOREGROUND")
524      (with-session-lock (*session*)
525        (let ((int-t (session-interactive-threads *session*)))
526          (when (eq (car int-t) *current-thread*)
527            (unless was-foreground
528              (format *query-io* "Resuming thread ~A~%" *current-thread*))
529            (return-from get-foreground t))
530          (setf was-foreground nil)
531          (unless (member *current-thread* int-t)
532            (setf (cdr (last int-t))
533                  (list *current-thread*)))
534          (condition-wait
535           (session-interactive-threads-queue *session*)
536           (session-lock *session*)))))))
537
538 (defun release-foreground (&optional next)
539   #!+sb-doc
540   "Background this thread.  If NEXT is supplied, arrange for it to
541 have the foreground next."
542   #!-sb-thread (declare (ignore next))
543   #!-sb-thread nil
544   #!+sb-thread
545   (with-session-lock (*session*)
546     (when (rest (session-interactive-threads *session*))
547       (setf (session-interactive-threads *session*)
548             (delete *current-thread* (session-interactive-threads *session*))))
549     (when next
550       (setf (session-interactive-threads *session*)
551             (list* next
552                    (delete next (session-interactive-threads *session*)))))
553     (condition-broadcast (session-interactive-threads-queue *session*))))
554
555 (defun foreground-thread ()
556   (car (session-interactive-threads *session*)))
557
558 (defun make-listener-thread (tty-name)
559   (assert (probe-file tty-name))
560   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
561          (out (sb!unix:unix-dup in))
562          (err (sb!unix:unix-dup in)))
563     (labels ((thread-repl ()
564                (sb!unix::unix-setsid)
565                (let* ((sb!impl::*stdin*
566                        (make-fd-stream in :input t :buffering :line
567                                        :dual-channel-p t))
568                       (sb!impl::*stdout*
569                        (make-fd-stream out :output t :buffering :line
570                                               :dual-channel-p t))
571                       (sb!impl::*stderr*
572                        (make-fd-stream err :output t :buffering :line
573                                               :dual-channel-p t))
574                       (sb!impl::*tty*
575                        (make-fd-stream err :input t :output t
576                                               :buffering :line
577                                               :dual-channel-p t))
578                       (sb!impl::*descriptor-handlers* nil))
579                  (with-new-session ()
580                    (unwind-protect
581                         (sb!impl::toplevel-repl nil)
582                      (sb!int:flush-standard-output-streams))))))
583       (make-thread #'thread-repl))))
584
585 ;;;; the beef
586
587 (defun make-thread (function &key name)
588   #!+sb-doc
589   "Create a new thread of NAME that runs FUNCTION. When the function
590 returns the thread exits."
591   #!-sb-thread (declare (ignore function name))
592   #!-sb-thread (error "Not supported in unithread builds.")
593   #!+sb-thread
594   (let* ((thread (%make-thread :name name))
595          (setup-sem (make-semaphore :name "Thread setup semaphore"))
596          (real-function (coerce function 'function))
597          (initial-function
598           (lambda ()
599             ;; In time we'll move some of the binding presently done in C
600             ;; here too.
601             ;;
602             ;; KLUDGE: Here we have a magic list of variables that are
603             ;; not thread-safe for one reason or another.  As people
604             ;; report problems with the thread safety of certain
605             ;; variables, (e.g. "*print-case* in multiple threads
606             ;; broken", sbcl-devel 2006-07-14), we add a few more
607             ;; bindings here.  The Right Thing is probably some variant
608             ;; of Allegro's *cl-default-special-bindings*, as that is at
609             ;; least accessible to users to secure their own libraries.
610             ;;   --njf, 2006-07-15
611             (let ((*current-thread* thread)
612                   (sb!kernel::*restart-clusters* nil)
613                   (sb!kernel::*handler-clusters* nil)
614                   (sb!kernel::*condition-restarts* nil)
615                   (sb!impl::*step-out* nil)
616                   ;; internal printer variables
617                   (sb!impl::*previous-case* nil)
618                   (sb!impl::*previous-readtable-case* nil)
619                   (sb!impl::*merge-sort-temp-vector* (vector)) ; keep these small!
620                   (sb!impl::*zap-array-data-temp* (vector))    ;
621                   (sb!impl::*internal-symbol-output-fun* nil)
622                   (sb!impl::*descriptor-handlers* nil)) ; serve-event
623               (setf (thread-os-thread thread) (current-thread-sap-id))
624               (with-mutex (*all-threads-lock*)
625                 (push thread *all-threads*))
626               (with-session-lock (*session*)
627                 (push thread (session-threads *session*)))
628               (setf (thread-%alive-p thread) t)
629               (signal-semaphore setup-sem)
630               ;; can't use handling-end-of-the-world, because that flushes
631               ;; output streams, and we don't necessarily have any (or we
632               ;; could be sharing them)
633               (catch 'sb!impl::toplevel-catcher
634                 (catch 'sb!impl::%end-of-the-world
635                   (with-simple-restart
636                       (terminate-thread
637                        (format nil
638                                "~~@<Terminate this thread (~A)~~@:>"
639                                *current-thread*))
640                     (unwind-protect
641                          (progn
642                            ;; now that most things have a chance to
643                            ;; work properly without messing up other
644                            ;; threads, it's time to enable signals
645                            (sb!unix::reset-signal-mask)
646                            (funcall real-function))
647                       ;; we're going down, can't handle
648                       ;; interrupts sanely anymore
649                       (let ((sb!impl::*gc-inhibit* t))
650                         (block-blockable-signals)
651                         (setf (thread-%alive-p thread) nil)
652                         (setf (thread-os-thread thread) nil)
653                         ;; and remove what can be the last
654                         ;; reference to this thread
655                         (handle-thread-exit thread)))))))
656             (values))))
657     ;; Keep INITIAL-FUNCTION pinned until the child thread is
658     ;; initialized properly.
659     (with-pinned-objects (initial-function)
660       (let ((os-thread
661              (%create-thread
662               (sb!kernel:get-lisp-obj-address initial-function))))
663         (when (zerop os-thread)
664           (error "Can't create a new thread"))
665         (wait-on-semaphore setup-sem)
666         thread))))
667
668 (defun destroy-thread (thread)
669   #!+sb-doc
670   "Deprecated. Same as TERMINATE-THREAD."
671   (terminate-thread thread))
672
673 (define-condition interrupt-thread-error (error)
674   ((thread :reader interrupt-thread-error-thread :initarg :thread))
675   #!+sb-doc
676   (:documentation "Interrupting thread failed.")
677   (:report (lambda (c s)
678              (format s "Interrupt thread failed: thread ~A has exited."
679                      (interrupt-thread-error-thread c)))))
680
681 #!+sb-doc
682 (setf (sb!kernel:fdocumentation 'interrupt-thread-error-thread 'function)
683       "The thread that was not interrupted.")
684
685 (defmacro with-interruptions-lock ((thread) &body body)
686   `(without-interrupts
687      (with-mutex ((thread-interruptions-lock ,thread))
688        ,@body)))
689
690 ;; Called from the signal handler.
691 (defun run-interruption ()
692   (in-interruption ()
693     (loop
694        (let ((interruption (with-interruptions-lock (*current-thread*)
695                              (pop (thread-interruptions *current-thread*)))))
696          (if interruption
697              (with-interrupts
698                (funcall interruption))
699              (return))))))
700
701 ;; The order of interrupt execution is peculiar. If thread A
702 ;; interrupts thread B with I1, I2 and B for some reason receives I1
703 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
704 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
705 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
706 ;; just one scenario, and the order of thread interrupt execution is
707 ;; undefined.
708 (defun interrupt-thread (thread function)
709   #!+sb-doc
710   "Interrupt the live THREAD and make it run FUNCTION. A moderate
711 degree of care is expected for use of INTERRUPT-THREAD, due to its
712 nature: if you interrupt a thread that was holding important locks
713 then do something that turns out to need those locks, you probably
714 won't like the effect."
715   #!-sb-thread (declare (ignore thread))
716   ;; not quite perfect, because it does not take WITHOUT-INTERRUPTS
717   ;; into account
718   #!-sb-thread
719   (funcall function)
720   #!+sb-thread
721   (if (eq thread *current-thread*)
722       (funcall function)
723       (let ((os-thread (thread-os-thread thread)))
724         (cond ((not os-thread)
725                (error 'interrupt-thread-error :thread thread))
726               (t
727                (with-interruptions-lock (thread)
728                  (push function (thread-interruptions thread)))
729                (when (minusp (signal-interrupt-thread os-thread))
730                  (error 'interrupt-thread-error :thread thread)))))))
731
732 (defun terminate-thread (thread)
733   #!+sb-doc
734   "Terminate the thread identified by THREAD, by causing it to run
735 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
736   (interrupt-thread thread 'sb!ext:quit))
737
738 ;;; internal use only.  If you think you need to use this, either you
739 ;;; are an SBCL developer, are doing something that you should discuss
740 ;;; with an SBCL developer first, or are doing something that you
741 ;;; should probably discuss with a professional psychiatrist first
742 #!+sb-thread
743 (defun thread-sap-for-id (id)
744   (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
745     (loop
746      (when (sap= thread-sap (int-sap 0)) (return nil))
747      (let ((os-thread (sap-ref-word thread-sap
748                                     (* sb!vm:n-word-bytes
749                                        sb!vm::thread-os-thread-slot))))
750        (when (= os-thread id) (return thread-sap))
751        (setf thread-sap
752              (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
753                                         sb!vm::thread-next-slot)))))))
754
755 #!+sb-thread
756 (defun symbol-value-in-thread (symbol thread-sap)
757   (let* ((index (sb!vm::symbol-tls-index symbol))
758          (tl-val (sap-ref-word thread-sap
759                                (* sb!vm:n-word-bytes index))))
760     (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
761         (sb!vm::symbol-global-value symbol)
762         (sb!kernel:make-lisp-obj tl-val))))
763
764 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
765   (sb!vm::locked-symbol-global-value-add symbol-name delta))
766
767 ;;; Stepping
768
769 (defun thread-stepping ()
770   (sb!kernel:make-lisp-obj
771    (sap-ref-word (current-thread-sap)
772                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
773
774 (defun (setf thread-stepping) (value)
775   (setf (sap-ref-word (current-thread-sap)
776                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
777         (sb!kernel:get-lisp-obj-address value)))