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