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