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