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