1.0.24.27: target-thread cosmetics
[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   (print-unreadable-object (thread stream :type t :identity t)
43     (let* ((cookie (list thread))
44            (info (if (thread-alive-p thread)
45                      :running
46                      (multiple-value-list
47                       (join-thread thread :default cookie))))
48            (state (if (eq :running info)
49                       info
50                       (if (eq cookie (car info))
51                           :aborted
52                           :finished)))
53            (values (when (eq :finished state) info)))
54       (format stream
55               "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
56               (thread-name thread)
57               (eq :finished state)
58               state
59               values))))
60
61 (defun thread-alive-p (thread)
62   #!+sb-doc
63   "Check if THREAD is running."
64   (thread-%alive-p thread))
65
66 ;; A thread is eligible for gc iff it has finished and there are no
67 ;; more references to it. This list is supposed to keep a reference to
68 ;; all running threads.
69 (defvar *all-threads* ())
70 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
71
72 (defvar *default-alloc-signal* nil)
73
74 (defmacro with-all-threads-lock (&body body)
75   `(with-system-mutex (*all-threads-lock*)
76      ,@body))
77
78 (defun list-all-threads ()
79   #!+sb-doc
80   "Return a list of the live threads."
81   (with-all-threads-lock
82     (copy-list *all-threads*)))
83
84 (declaim (inline current-thread-sap))
85 (defun current-thread-sap ()
86   (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
87
88 (declaim (inline current-thread-os-thread))
89 (defun current-thread-os-thread ()
90   (sap-int
91    (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
92
93 (defun init-initial-thread ()
94   (/show0 "Entering INIT-INITIAL-THREAD")
95   (let ((initial-thread (%make-thread :name "initial thread"
96                                       :%alive-p t
97                                       :os-thread (current-thread-os-thread))))
98     (setq *current-thread* initial-thread)
99     ;; Either *all-threads* is empty or it contains exactly one thread
100     ;; in case we are in reinit since saving core with multiple
101     ;; threads doesn't work.
102     (setq *all-threads* (list initial-thread))))
103 \f
104
105 ;;;; Aliens, low level stuff
106
107 #!+sb-thread
108 (progn
109   ;; FIXME it would be good to define what a thread id is or isn't
110   ;; (our current assumption is that it's a fixnum).  It so happens
111   ;; that on Linux it's a pid, but it might not be on posix thread
112   ;; implementations.
113   (define-alien-routine ("create_thread" %create-thread)
114       unsigned-long (lisp-fun-address unsigned-long))
115
116   (define-alien-routine "signal_interrupt_thread"
117       integer (os-thread unsigned-long))
118
119   (define-alien-routine "block_deferrable_signals"
120       void)
121
122   #!+sb-lutex
123   (progn
124     (declaim (inline %lutex-init %lutex-wait %lutex-wake
125                      %lutex-lock %lutex-unlock))
126
127     (define-alien-routine ("lutex_init" %lutex-init)
128         int (lutex unsigned-long))
129
130     (define-alien-routine ("lutex_wait" %lutex-wait)
131         int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
132
133     (define-alien-routine ("lutex_wake" %lutex-wake)
134         int (lutex unsigned-long) (n int))
135
136     (define-alien-routine ("lutex_lock" %lutex-lock)
137         int (lutex unsigned-long))
138
139     (define-alien-routine ("lutex_trylock" %lutex-trylock)
140         int (lutex unsigned-long))
141
142     (define-alien-routine ("lutex_unlock" %lutex-unlock)
143         int (lutex unsigned-long))
144
145     (define-alien-routine ("lutex_destroy" %lutex-destroy)
146         int (lutex unsigned-long))
147
148     ;; FIXME: Defining a whole bunch of alien-type machinery just for
149     ;; passing primitive lutex objects directly to foreign functions
150     ;; doesn't seem like fun right now. So instead we just manually
151     ;; pin the lutex, get its address, and let the callee untag it.
152     (defmacro with-lutex-address ((name lutex) &body body)
153       `(let ((,name ,lutex))
154          (with-pinned-objects (,name)
155            (let ((,name (get-lisp-obj-address ,name)))
156              ,@body))))
157
158     (defun make-lutex ()
159       (/show0 "Entering MAKE-LUTEX")
160       ;; Suppress GC until the lutex has been properly registered with
161       ;; the GC.
162       (without-gcing
163         (let ((lutex (sb!vm::%make-lutex)))
164           (/show0 "LUTEX=..")
165           (/hexstr lutex)
166           (with-lutex-address (lutex lutex)
167             (%lutex-init lutex))
168           lutex))))
169
170   #!-sb-lutex
171   (progn
172     (declaim (inline futex-wait %futex-wait futex-wake))
173
174     (define-alien-routine ("futex_wait" %futex-wait)
175         int (word unsigned-long) (old-value unsigned-long)
176         (to-sec long) (to-usec unsigned-long))
177
178     (defun futex-wait (word old to-sec to-usec)
179       (with-interrupts
180         (%futex-wait word old to-sec to-usec)))
181
182     (define-alien-routine "futex_wake"
183         int (word unsigned-long) (n unsigned-long))))
184
185 ;;; used by debug-int.lisp to access interrupt contexts
186 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
187 #!-sb-thread
188 (defun sb!vm::current-thread-offset-sap (n)
189   (declare (type (unsigned-byte 27) n))
190   (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
191                (* n sb!vm:n-word-bytes)))
192
193 #!+sb-thread
194 (defun sb!vm::current-thread-offset-sap (n)
195   (declare (type (unsigned-byte 27) n))
196   (sb!vm::current-thread-offset-sap n))
197 \f
198
199 ;;;; Spinlocks
200
201 (declaim (inline get-spinlock release-spinlock))
202
203 ;;; Should always be called with interrupts disabled.
204 (defun get-spinlock (spinlock)
205   (declare (optimize (speed 3) (safety 0)))
206   (let* ((new *current-thread*)
207          (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
208     (when old
209       (when (eq old new)
210         (error "Recursive lock attempt on ~S." spinlock))
211       #!+sb-thread
212       (flet ((cas ()
213                (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
214                    (thread-yield)
215                    (return-from get-spinlock t))))
216         (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
217             ;; If interrupts are enabled, but we are allowed to enabled them,
218             ;; check for pending interrupts every once in a while.
219             (loop
220               (loop repeat 128 do (cas)) ; 128 is arbitrary here
221               (sb!unix::%check-interrupts))
222             (loop (cas)))))
223     t))
224
225 (defun release-spinlock (spinlock)
226   (declare (optimize (speed 3) (safety 0)))
227   ;; Simply setting SPINLOCK-VALUE to NIL is not enough as it does not
228   ;; propagate to other processors, plus without a memory barrier the
229   ;; CPU might reorder instructions allowing code from the critical
230   ;; section to leak out. Use COMPARE-AND-SWAP for the memory barrier
231   ;; effect and do some sanity checking while we are at it.
232   (unless (eq *current-thread*
233               (sb!ext:compare-and-swap (spinlock-value spinlock)
234                                        *current-thread* nil))
235     (error "Only the owner can release the spinlock ~S." spinlock)))
236 \f
237
238 ;;;; Mutexes
239
240 #!+sb-doc
241 (setf (fdocumentation 'make-mutex 'function)
242       "Create a mutex."
243       (fdocumentation 'mutex-name 'function)
244       "The name of the mutex. Setfable.")
245
246 #!+(and sb-thread (not sb-lutex))
247 (progn
248   (define-structure-slot-addressor mutex-state-address
249       :structure mutex
250       :slot state)
251   ;; Important: current code assumes these are fixnums or other
252   ;; lisp objects that don't need pinning.
253   (defconstant +lock-free+ 0)
254   (defconstant +lock-taken+ 1)
255   (defconstant +lock-contested+ 2))
256
257 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
258   #!+sb-doc
259   "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
260 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
261 non-NIL and the mutex is in use, sleep until it is available.
262
263 Note: using GET-MUTEX to assign a MUTEX to another thread then the
264 current one is not recommended, and liable to be deprecated.
265
266 GET-MUTEX is not interrupt safe. The correct way to call it is:
267
268  (WITHOUT-INTERRUPTS
269    ...
270    (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
271    ...)
272
273 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
274 call while the mutex is in an inconsistent state while
275 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
276
277 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
278 directly."
279   (declare (type mutex mutex) (optimize (speed 3))
280            #!-sb-thread (ignore waitp))
281   (unless new-owner
282     (setq new-owner *current-thread*))
283   (let ((old (mutex-%owner mutex)))
284     (when (eq new-owner old)
285       (error "Recursive lock attempt ~S." mutex))
286     #!-sb-thread
287     (if old
288         (error "Strange deadlock on ~S in an unithreaded build?" mutex)
289         (setf (mutex-%owner mutex) new-owner)))
290   #!+sb-thread
291   (progn
292     ;; FIXME: Lutexes do not currently support deadlines, as at least
293     ;; on Darwin pthread_foo_timedbar functions are not supported:
294     ;; this means that we probably need to use the Carbon multiprocessing
295     ;; functions on Darwin.
296     ;;
297     ;; FIXME: This is definitely not interrupt safe: what happens if
298     ;; we get hit (1) during the lutex calls (ok, they may be safe,
299     ;; but has that been checked?) (2) after the lutex call, but
300     ;; before setting the mutex owner.
301     #!+sb-lutex
302     (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
303                    (if waitp
304                        (with-interrupts (%lutex-lock lutex))
305                        (%lutex-trylock lutex))))
306       (setf (mutex-%owner mutex) new-owner)
307       t)
308     #!-sb-lutex
309     (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
310                                         +lock-free+
311                                         +lock-taken+)))
312       (unless (or (eql +lock-free+ old) (not waitp))
313         (tagbody
314          :retry
315            (when (or (eql +lock-contested+ old)
316                      (not (eql +lock-free+
317                                (sb!ext:compare-and-swap (mutex-state mutex)
318                                                         +lock-taken+
319                                                         +lock-contested+))))
320              ;; Wait on the contested lock.
321              (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
322                (when (= 1 (with-pinned-objects (mutex)
323                             (futex-wait (mutex-state-address mutex)
324                                         (get-lisp-obj-address +lock-contested+)
325                                         (or to-sec -1)
326                                         (or to-usec 0))))
327                  (signal-deadline))))
328            (setf old (sb!ext:compare-and-swap (mutex-state mutex)
329                                               +lock-free+
330                                               +lock-contested+))
331            ;; Did we get it?
332            (unless (eql +lock-free+ old)
333              (go :retry))))
334       (cond ((eql +lock-free+ old)
335              (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
336                                                   nil new-owner)))
337                (when prev
338                  (bug "Old owner in free mutex: ~S" prev))
339                t))
340             (waitp
341              (bug "Failed to acquire lock with WAITP."))))))
342
343 (defun release-mutex (mutex)
344   #!+sb-doc
345   "Release MUTEX by setting it to NIL. Wake up threads waiting for
346 this mutex.
347
348 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
349 around calls to it.
350
351 Signals a WARNING is current thread is not the current owner of the
352 mutex."
353   (declare (type mutex mutex))
354   ;; Order matters: set owner to NIL before releasing state.
355   (let* ((self *current-thread*)
356          (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
357     (unless  (eql self old-owner)
358       (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
359       (setf (mutex-%owner mutex) nil)))
360   #!+sb-thread
361   (progn
362     #!+sb-lutex
363     (with-lutex-address (lutex (mutex-lutex mutex))
364       (%lutex-unlock lutex))
365     #!-sb-lutex
366     (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
367                                         +lock-taken+ +lock-free+)))
368       (when (eql old +lock-contested+)
369         (sb!ext:compare-and-swap (mutex-state mutex)
370                                  +lock-contested+ +lock-free+)
371         (with-pinned-objects (mutex)
372           (futex-wake (mutex-state-address mutex) 1))))
373     nil))
374 \f
375
376 ;;;; Waitqueues/condition variables
377
378 (defstruct (waitqueue (:constructor %make-waitqueue))
379   #!+sb-doc
380   "Waitqueue type."
381   (name nil :type (or null simple-string))
382   #!+(and sb-lutex sb-thread)
383   (lutex (make-lutex))
384   #!-sb-lutex
385   (data nil))
386
387 (defun make-waitqueue (&key name)
388   #!+sb-doc
389   "Create a waitqueue."
390   (%make-waitqueue :name name))
391
392 #!+sb-doc
393 (setf (fdocumentation 'waitqueue-name 'function)
394       "The name of the waitqueue. Setfable.")
395
396 #!+(and sb-thread (not sb-lutex))
397 (define-structure-slot-addressor waitqueue-data-address
398     :structure waitqueue
399     :slot data)
400
401 (defun condition-wait (queue mutex)
402   #!+sb-doc
403   "Atomically release MUTEX and enqueue ourselves on QUEUE.  Another
404 thread may subsequently notify us using CONDITION-NOTIFY, at which
405 time we reacquire MUTEX and return to the caller."
406   #!-sb-thread (declare (ignore queue))
407   (assert mutex)
408   #!-sb-thread (error "Not supported in unithread builds.")
409   #!+sb-thread
410   (let ((me *current-thread*))
411     (assert (eq me (mutex-%owner mutex)))
412     (/show0 "CONDITION-WAITing")
413     #!+sb-lutex
414     ;; Need to disable interrupts so that we don't miss setting the
415     ;; owner on our way out. (pthread_cond_wait handles the actual
416     ;; re-acquisition.)
417     (without-interrupts
418       (unwind-protect
419            (progn
420              (setf (mutex-%owner mutex) nil)
421              (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
422                (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
423                  (with-local-interrupts
424                    (%lutex-wait queue-lutex-address mutex-lutex-address)))))
425         (setf (mutex-%owner mutex) me)))
426     #!-sb-lutex
427     ;; Need to disable interrupts so that we don't miss grabbing the
428     ;; mutex on our way out.
429     (without-interrupts
430       (unwind-protect
431            (let ((me *current-thread*))
432              ;; This setf becomes visible to other CPUS due to the
433              ;; usual memory barrier semantics of lock
434              ;; acquire/release.
435              (setf (waitqueue-data queue) me)
436              (release-mutex mutex)
437              ;; Now we go to sleep using futex-wait. If anyone else
438              ;; manages to grab MUTEX and call CONDITION-NOTIFY during
439              ;; this comment, it will change queue->data, and so
440              ;; futex-wait returns immediately instead of sleeping.
441              ;; Ergo, no lost wakeup. We may get spurious wakeups, but
442              ;; that's ok.
443              (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
444                (when (= 1 (with-pinned-objects (queue me)
445                             (allow-with-interrupts
446                               (futex-wait (waitqueue-data-address queue)
447                                           (get-lisp-obj-address me)
448                                           ;; our way if saying "no
449                                           ;; timeout":
450                                           (or to-sec -1)
451                                           (or to-usec 0)))))
452                  (signal-deadline))))
453         ;; If we are interrupted while waiting, we should do these
454         ;; things before returning. Ideally, in the case of an
455         ;; unhandled signal, we should do them before entering the
456         ;; debugger, but this is better than nothing.
457         (get-mutex mutex)))))
458
459 (defun condition-notify (queue &optional (n 1))
460   #!+sb-doc
461   "Notify N threads waiting on QUEUE. The same mutex that is used in
462 the correspoinding condition-wait must be held by this thread during
463 this call."
464   #!-sb-thread (declare (ignore queue n))
465   #!-sb-thread (error "Not supported in unithread builds.")
466   #!+sb-thread
467   (declare (type (and fixnum (integer 1)) n))
468   (/show0 "Entering CONDITION-NOTIFY")
469   #!+sb-thread
470   (progn
471     #!+sb-lutex
472     (with-lutex-address (lutex (waitqueue-lutex queue))
473       (%lutex-wake lutex n))
474     ;; no problem if >1 thread notifies during the comment in
475     ;; condition-wait: as long as the value in queue-data isn't the
476     ;; waiting thread's id, it matters not what it is
477     ;; XXX we should do something to ensure that the result of this setf
478     ;; is visible to all CPUs
479     #!-sb-lutex
480     (let ((me *current-thread*))
481       (progn
482         (setf (waitqueue-data queue) me)
483         (with-pinned-objects (queue)
484           (futex-wake (waitqueue-data-address queue) n))))))
485
486 (defun condition-broadcast (queue)
487   #!+sb-doc
488   "Notify all threads waiting on QUEUE."
489   (condition-notify queue
490                     ;; On a 64-bit platform truncating M-P-F to an int
491                     ;; results in -1, which wakes up only one thread.
492                     (ldb (byte 29 0)
493                          most-positive-fixnum)))
494 \f
495
496 ;;;; Semaphores
497
498 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
499   #!+sb-doc
500   "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
501 should be considered an implementation detail, and may change in the
502 future."
503   (name nil :type (or null simple-string))
504   (%count 0 :type (integer 0))
505   (waitcount 0 :type (integer 0))
506   (mutex (make-mutex))
507   (queue (make-waitqueue)))
508
509 (setf (fdocumentation 'semaphore-name 'function)
510       "The name of the semaphore INSTANCE. Setfable.")
511
512 (declaim (inline semaphore-count))
513 (defun semaphore-count (instance)
514   "Returns the current count of the semaphore INSTANCE."
515   (semaphore-%count instance))
516
517 (defun make-semaphore (&key name (count 0))
518   #!+sb-doc
519   "Create a semaphore with the supplied COUNT and NAME."
520   (%make-semaphore name count))
521
522 (defun wait-on-semaphore (semaphore)
523   #!+sb-doc
524   "Decrement the count of SEMAPHORE if the count would not be
525 negative. Else blocks until the semaphore can be decremented."
526   ;; A more direct implementation based directly on futexes should be
527   ;; possible.
528   ;;
529   ;; We need to disable interrupts so that we don't forget to
530   ;; decrement the waitcount (which would happen if an asynch
531   ;; interrupt should catch us on our way out from the loop.)
532   (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
533     ;; Quick check: is it positive? If not, enter the wait loop.
534     (let ((count (semaphore-%count semaphore)))
535       (if (plusp count)
536           (setf (semaphore-%count semaphore) (1- count))
537           (unwind-protect
538                (progn
539                  (incf (semaphore-waitcount semaphore))
540                  (loop until (plusp (setf count (semaphore-%count semaphore)))
541                        do (condition-wait (semaphore-queue semaphore)
542                                           (semaphore-mutex semaphore)))
543                  (setf (semaphore-%count semaphore) (1- count)))
544             (decf (semaphore-waitcount semaphore)))))))
545
546 (defun signal-semaphore (semaphore &optional (n 1))
547   #!+sb-doc
548   "Increment the count of SEMAPHORE by N. If there are threads waiting
549 on this semaphore, then N of them is woken up."
550   (declare (type (integer 1) n))
551   ;; Need to disable interrupts so that we don't lose a wakeup after
552   ;; we have incremented the count.
553   (with-system-mutex ((semaphore-mutex semaphore))
554     (let ((waitcount (semaphore-waitcount semaphore))
555           (count (incf (semaphore-%count semaphore) n)))
556       (when (plusp waitcount)
557         (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
558 \f
559
560 ;;;; Job control, independent listeners
561
562 (defstruct session
563   (lock (make-mutex :name "session lock"))
564   (threads nil)
565   (interactive-threads nil)
566   (interactive-threads-queue (make-waitqueue)))
567
568 (defvar *session* nil)
569
570 ;;; The debugger itself tries to acquire the session lock, don't let
571 ;;; funny situations (like getting a sigint while holding the session
572 ;;; lock) occur. At the same time we need to allow interrupts while
573 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
574 ;;; be interruptible.
575 ;;;
576 ;;; Take care: we sometimes need to obtain the session lock while
577 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
578 ;;; _after_ getting a session lock! (Deadlock risk.)
579 ;;;
580 ;;; FIXME: It would be good to have ordered locks to ensure invariants
581 ;;; like the above.
582 (defmacro with-session-lock ((session) &body body)
583   `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
584      ,@body))
585
586 (defun new-session ()
587   (make-session :threads (list *current-thread*)
588                 :interactive-threads (list *current-thread*)))
589
590 (defun init-job-control ()
591   (/show0 "Entering INIT-JOB-CONTROL")
592   (setf *session* (new-session))
593   (/show0 "Exiting INIT-JOB-CONTROL"))
594
595 (defun %delete-thread-from-session (thread session)
596   (with-session-lock (session)
597     (setf (session-threads session)
598           (delete thread (session-threads session))
599           (session-interactive-threads session)
600           (delete thread (session-interactive-threads session)))))
601
602 (defun call-with-new-session (fn)
603   (%delete-thread-from-session *current-thread* *session*)
604   (let ((*session* (new-session)))
605     (funcall fn)))
606
607 (defmacro with-new-session (args &body forms)
608   (declare (ignore args))               ;for extensibility
609   (sb!int:with-unique-names (fb-name)
610     `(labels ((,fb-name () ,@forms))
611       (call-with-new-session (function ,fb-name)))))
612
613 ;;; Remove thread from its session, if it has one.
614 #!+sb-thread
615 (defun handle-thread-exit (thread)
616   (/show0 "HANDLING THREAD EXIT")
617   ;; We're going down, can't handle interrupts sanely anymore. GC
618   ;; remains enabled.
619   (block-deferrable-signals)
620   ;; Lisp-side cleanup
621   (with-all-threads-lock
622     (setf (thread-%alive-p thread) nil)
623     (setf (thread-os-thread thread) nil)
624     (setq *all-threads* (delete thread *all-threads*))
625     (when *session*
626       (%delete-thread-from-session thread *session*)))
627   #!+sb-lutex
628   (without-gcing
629     (/show0 "FREEING MUTEX LUTEX")
630     (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
631       (%lutex-destroy lutex))))
632
633 (defun terminate-session ()
634   #!+sb-doc
635   "Kill all threads in session except for this one.  Does nothing if current
636 thread is not the foreground thread."
637   ;; FIXME: threads created in other threads may escape termination
638   (let ((to-kill
639          (with-session-lock (*session*)
640            (and (eq *current-thread*
641                     (car (session-interactive-threads *session*)))
642                 (session-threads *session*)))))
643     ;; do the kill after dropping the mutex; unwind forms in dying
644     ;; threads may want to do session things
645     (dolist (thread to-kill)
646       (unless (eq thread *current-thread*)
647         ;; terminate the thread but don't be surprised if it has
648         ;; exited in the meantime
649         (handler-case (terminate-thread thread)
650           (interrupt-thread-error ()))))))
651
652 ;;; called from top of invoke-debugger
653 (defun debugger-wait-until-foreground-thread (stream)
654   "Returns T if thread had been running in background, NIL if it was
655 interactive."
656   (declare (ignore stream))
657   #!-sb-thread nil
658   #!+sb-thread
659   (prog1
660       (with-session-lock (*session*)
661         (not (member *current-thread*
662                      (session-interactive-threads *session*))))
663     (get-foreground)))
664
665 (defun get-foreground ()
666   #!-sb-thread t
667   #!+sb-thread
668   (let ((was-foreground t))
669     (loop
670      (/show0 "Looping in GET-FOREGROUND")
671      (with-session-lock (*session*)
672        (let ((int-t (session-interactive-threads *session*)))
673          (when (eq (car int-t) *current-thread*)
674            (unless was-foreground
675              (format *query-io* "Resuming thread ~A~%" *current-thread*))
676            (return-from get-foreground t))
677          (setf was-foreground nil)
678          (unless (member *current-thread* int-t)
679            (setf (cdr (last int-t))
680                  (list *current-thread*)))
681          (condition-wait
682           (session-interactive-threads-queue *session*)
683           (session-lock *session*)))))))
684
685 (defun release-foreground (&optional next)
686   #!+sb-doc
687   "Background this thread.  If NEXT is supplied, arrange for it to
688 have the foreground next."
689   #!-sb-thread (declare (ignore next))
690   #!-sb-thread nil
691   #!+sb-thread
692   (with-session-lock (*session*)
693     (when (rest (session-interactive-threads *session*))
694       (setf (session-interactive-threads *session*)
695             (delete *current-thread* (session-interactive-threads *session*))))
696     (when next
697       (setf (session-interactive-threads *session*)
698             (list* next
699                    (delete next (session-interactive-threads *session*)))))
700     (condition-broadcast (session-interactive-threads-queue *session*))))
701
702 (defun foreground-thread ()
703   (car (session-interactive-threads *session*)))
704
705 (defun make-listener-thread (tty-name)
706   (assert (probe-file tty-name))
707   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
708          (out (sb!unix:unix-dup in))
709          (err (sb!unix:unix-dup in)))
710     (labels ((thread-repl ()
711                (sb!unix::unix-setsid)
712                (let* ((sb!impl::*stdin*
713                        (make-fd-stream in :input t :buffering :line
714                                        :dual-channel-p t))
715                       (sb!impl::*stdout*
716                        (make-fd-stream out :output t :buffering :line
717                                               :dual-channel-p t))
718                       (sb!impl::*stderr*
719                        (make-fd-stream err :output t :buffering :line
720                                               :dual-channel-p t))
721                       (sb!impl::*tty*
722                        (make-fd-stream err :input t :output t
723                                               :buffering :line
724                                               :dual-channel-p t))
725                       (sb!impl::*descriptor-handlers* nil))
726                  (with-new-session ()
727                    (unwind-protect
728                         (sb!impl::toplevel-repl nil)
729                      (sb!int:flush-standard-output-streams))))))
730       (make-thread #'thread-repl))))
731 \f
732
733 ;;;; The beef
734
735 (defun make-thread (function &key name)
736   #!+sb-doc
737   "Create a new thread of NAME that runs FUNCTION. When the function
738 returns the thread exits. The return values of FUNCTION are kept
739 around and can be retrieved by JOIN-THREAD."
740   #!-sb-thread (declare (ignore function name))
741   #!-sb-thread (error "Not supported in unithread builds.")
742   #!+sb-thread
743   (let* ((thread (%make-thread :name name))
744          (setup-sem (make-semaphore :name "Thread setup semaphore"))
745          (real-function (coerce function 'function))
746          (initial-function
747           (lambda ()
748             ;; In time we'll move some of the binding presently done in C
749             ;; here too.
750             ;;
751             ;; KLUDGE: Here we have a magic list of variables that are
752             ;; not thread-safe for one reason or another.  As people
753             ;; report problems with the thread safety of certain
754             ;; variables, (e.g. "*print-case* in multiple threads
755             ;; broken", sbcl-devel 2006-07-14), we add a few more
756             ;; bindings here.  The Right Thing is probably some variant
757             ;; of Allegro's *cl-default-special-bindings*, as that is at
758             ;; least accessible to users to secure their own libraries.
759             ;;   --njf, 2006-07-15
760             (let* ((*current-thread* thread)
761                    (*restart-clusters* nil)
762                    (*handler-clusters* (sb!kernel::initial-handler-clusters))
763                    (*condition-restarts* nil)
764                    (sb!impl::*deadline* nil)
765                    (sb!impl::*step-out* nil)
766                    ;; internal printer variables
767                    (sb!impl::*previous-case* nil)
768                    (sb!impl::*previous-readtable-case* nil)
769                    (empty (vector))
770                    (sb!impl::*merge-sort-temp-vector* empty)
771                    (sb!impl::*zap-array-data-temp* empty)
772                    (sb!impl::*internal-symbol-output-fun* nil)
773                    (sb!impl::*descriptor-handlers* nil)) ; serve-event
774               ;; Binding from C
775               (setf sb!vm:*alloc-signal* *default-alloc-signal*)
776               (setf (thread-os-thread thread) (current-thread-os-thread))
777               (with-mutex ((thread-result-lock thread))
778                 (with-all-threads-lock
779                   (push thread *all-threads*))
780                 (with-session-lock (*session*)
781                   (push thread (session-threads *session*)))
782                 (setf (thread-%alive-p thread) t)
783                 (signal-semaphore setup-sem)
784                 ;; can't use handling-end-of-the-world, because that flushes
785                 ;; output streams, and we don't necessarily have any (or we
786                 ;; could be sharing them)
787                 (catch 'sb!impl::toplevel-catcher
788                   (catch 'sb!impl::%end-of-the-world
789                     (with-simple-restart
790                         (terminate-thread
791                          (format nil
792                                  "~~@<Terminate this thread (~A)~~@:>"
793                                  *current-thread*))
794                       (unwind-protect
795                            (progn
796                              ;; now that most things have a chance to
797                              ;; work properly without messing up other
798                              ;; threads, it's time to enable signals
799                              (sb!unix::reset-signal-mask)
800                              (setf (thread-result thread)
801                                    (cons t
802                                          (multiple-value-list
803                                           (funcall real-function)))))
804                         (handle-thread-exit thread)))))))
805             (values))))
806     ;; Keep INITIAL-FUNCTION pinned until the child thread is
807     ;; initialized properly.
808     (with-pinned-objects (initial-function)
809       (let ((os-thread
810              (%create-thread
811               (get-lisp-obj-address initial-function))))
812         (when (zerop os-thread)
813           (error "Can't create a new thread"))
814         (wait-on-semaphore setup-sem)
815         thread))))
816
817 (define-condition join-thread-error (error)
818   ((thread :reader join-thread-error-thread :initarg :thread))
819   #!+sb-doc
820   (:documentation "Joining thread failed.")
821   (:report (lambda (c s)
822              (format s "Joining thread failed: thread ~A ~
823                         has not returned normally."
824                      (join-thread-error-thread c)))))
825
826 #!+sb-doc
827 (setf (fdocumentation 'join-thread-error-thread 'function)
828       "The thread that we failed to join.")
829
830 (defun join-thread (thread &key (default nil defaultp))
831   #!+sb-doc
832   "Suspend current thread until THREAD exits. Returns the result
833 values of the thread function. If the thread does not exit normally,
834 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
835   (with-mutex ((thread-result-lock thread))
836     (cond ((car (thread-result thread))
837            (values-list (cdr (thread-result thread))))
838           (defaultp
839            default)
840           (t
841            (error 'join-thread-error :thread thread)))))
842
843 (defun destroy-thread (thread)
844   #!+sb-doc
845   "Deprecated. Same as TERMINATE-THREAD."
846   (terminate-thread thread))
847
848 (define-condition interrupt-thread-error (error)
849   ((thread :reader interrupt-thread-error-thread :initarg :thread))
850   #!+sb-doc
851   (:documentation "Interrupting thread failed.")
852   (:report (lambda (c s)
853              (format s "Interrupt thread failed: thread ~A has exited."
854                      (interrupt-thread-error-thread c)))))
855
856 #!+sb-doc
857 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
858       "The thread that was not interrupted.")
859
860 (defmacro with-interruptions-lock ((thread) &body body)
861   `(with-system-mutex ((thread-interruptions-lock ,thread))
862      ,@body))
863
864 ;;; Called from the signal handler in C.
865 (defun run-interruption ()
866   (in-interruption ()
867     (loop
868        (let ((interruption (with-interruptions-lock (*current-thread*)
869                              (pop (thread-interruptions *current-thread*)))))
870          (if interruption
871              (with-interrupts
872                (funcall interruption))
873              (return))))))
874
875 ;;; The order of interrupt execution is peculiar. If thread A
876 ;;; interrupts thread B with I1, I2 and B for some reason receives I1
877 ;;; when FUN2 is already on the list, then it is FUN2 that gets to run
878 ;;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
879 ;;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
880 ;;; just one scenario, and the order of thread interrupt execution is
881 ;;; undefined.
882 (defun interrupt-thread (thread function)
883   #!+sb-doc
884   "Interrupt the live THREAD and make it run FUNCTION. A moderate
885 degree of care is expected for use of INTERRUPT-THREAD, due to its
886 nature: if you interrupt a thread that was holding important locks
887 then do something that turns out to need those locks, you probably
888 won't like the effect."
889   #!-sb-thread (declare (ignore thread))
890   #!-sb-thread
891   (with-interrupt-bindings
892     (with-interrupts (funcall function)))
893   #!+sb-thread
894   (if (eq thread *current-thread*)
895       (with-interrupt-bindings
896         (with-interrupts (funcall function)))
897       (let ((os-thread (thread-os-thread thread)))
898         (cond ((not os-thread)
899                (error 'interrupt-thread-error :thread thread))
900               (t
901                (with-interruptions-lock (thread)
902                  (push function (thread-interruptions thread)))
903                (when (minusp (signal-interrupt-thread os-thread))
904                  (error 'interrupt-thread-error :thread thread)))))))
905
906 (defun terminate-thread (thread)
907   #!+sb-doc
908   "Terminate the thread identified by THREAD, by causing it to run
909 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
910   (interrupt-thread thread 'sb!ext:quit))
911
912 (define-alien-routine "thread_yield" int)
913
914 #!+sb-doc
915 (setf (fdocumentation 'thread-yield 'function)
916       "Yield the processor to other threads.")
917
918 ;;; internal use only.  If you think you need to use these, either you
919 ;;; are an SBCL developer, are doing something that you should discuss
920 ;;; with an SBCL developer first, or are doing something that you
921 ;;; should probably discuss with a professional psychiatrist first
922 #!+sb-thread
923 (progn
924   (defun %thread-sap (thread)
925     (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
926           (target (thread-os-thread thread)))
927       (loop
928         (when (sap= thread-sap (int-sap 0)) (return nil))
929         (let ((os-thread (sap-ref-word thread-sap
930                                        (* sb!vm:n-word-bytes
931                                           sb!vm::thread-os-thread-slot))))
932           (when (= os-thread target) (return thread-sap))
933           (setf thread-sap
934                 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
935                                            sb!vm::thread-next-slot)))))))
936
937   (defun %symbol-value-in-thread (symbol thread)
938     (tagbody
939        ;; Prevent the dead from dying completely while we look for the
940        ;; TLS area...
941        (with-all-threads-lock
942          (if (thread-alive-p thread)
943              (let* ((offset (* sb!vm:n-word-bytes
944                                (sb!vm::symbol-tls-index symbol)))
945                     (tl-val (sap-ref-word (%thread-sap thread) offset)))
946                (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
947                    (go :unbound)
948                    (return-from %symbol-value-in-thread
949                      (values (make-lisp-obj tl-val) t))))
950              (return-from %symbol-value-in-thread (values nil nil))))
951      :unbound
952        (error "Cannot read thread-local symbol value: ~S unbound in ~S"
953               symbol thread)))
954
955   (defun %set-symbol-value-in-thread (symbol thread value)
956     (tagbody
957        (with-pinned-objects (value)
958          ;; Prevent the dead from dying completely while we look for
959          ;; the TLS area...
960          (with-all-threads-lock
961            (if (thread-alive-p thread)
962                (let* ((offset (* sb!vm:n-word-bytes
963                                  (sb!vm::symbol-tls-index symbol)))
964                       (sap (%thread-sap thread))
965                       (tl-val (sap-ref-word sap offset)))
966                  (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
967                      (go :unbound)
968                      (setf (sap-ref-word sap offset)
969                            (get-lisp-obj-address value)))
970                  (return-from %set-symbol-value-in-thread (values value t)))
971                (return-from %set-symbol-value-in-thread (values nil nil)))))
972      :unbound
973        (error "Cannot set thread-local symbol value: ~S unbound in ~S"
974               symbol thread))))
975
976 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
977   (sb!vm::locked-symbol-global-value-add symbol-name delta))
978 \f
979
980 ;;;; Stepping
981
982 (defun thread-stepping ()
983   (make-lisp-obj
984    (sap-ref-word (current-thread-sap)
985                  (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
986
987 (defun (setf thread-stepping) (value)
988   (setf (sap-ref-word (current-thread-sap)
989                       (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
990         (get-lisp-obj-address value)))