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