1 ;;;; support for threads in the target machine
3 ;;;; This software is part of the SBCL system. See the README file for
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.
12 (in-package "SB!THREAD")
16 (define-condition thread-error (error)
17 ((thread :reader thread-error-thread :initarg :thread))
20 "Conditions of type THREAD-ERROR are signalled when thread operations fail.
21 The offending thread is initialized by the :THREAD initialization argument and
22 read by the function THREAD-ERROR-THREAD."))
26 (fdocumentation 'thread-error-thread 'function)
27 "Return the offending thread that the THREAD-ERROR pertains to.")
29 (define-condition symbol-value-in-thread-error (cell-error thread-error)
30 ((info :reader symbol-value-in-thread-error-info :initarg :info))
32 (lambda (condition stream)
33 (destructuring-bind (op problem)
34 (symbol-value-in-thread-error-info condition)
35 (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
37 (cell-error-name condition)
38 (thread-error-thread condition)
40 (:unbound "the symbol is unbound in thread.")
41 (:dead "the thread has exited."))))))
44 "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to the
45 symbol being unbound in target thread, or the target thread having exited. The
46 offending symbol can be accessed using CELL-ERROR-NAME, and the offending
47 thread using THREAD-ERROR-THREAD."))
49 (define-condition join-thread-error (thread-error) ()
50 (:report (lambda (c s)
51 (format s "Joining thread failed: thread ~A ~
52 did not return normally."
53 (thread-error-thread c))))
56 "Signalled when joining a thread fails due to abnormal exit of the thread
57 to be joined. The offending thread can be accessed using
58 THREAD-ERROR-THREAD."))
60 (defun join-thread-error-thread (condition)
61 (thread-error-thread condition))
62 (define-compiler-macro join-thread-error-thread (condition)
63 (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
64 `(thread-error-thread ,condition))
68 (fdocumentation 'join-thread-error-thread 'function)
69 "The thread that we failed to join. Deprecated, use THREAD-ERROR-THREAD
72 (define-condition interrupt-thread-error (thread-error) ()
73 (:report (lambda (c s)
74 (format s "Interrupt thread failed: thread ~A has exited."
75 (thread-error-thread c))))
78 "Signalled when interrupting a thread fails because the thread has already
79 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
81 (defun interrupt-thread-error-thread (condition)
82 (thread-error-thread condition))
83 (define-compiler-macro interrupt-thread-error-thread (condition)
84 (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
85 `(thread-error-thread ,condition))
89 (fdocumentation 'interrupt-thread-error-thread 'function)
90 "The thread that was not interrupted. Deprecated, use THREAD-ERROR-THREAD
93 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
94 ;;; necessary because threads are only supported with the conservative
95 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
96 ;;; are treated as references.
98 ;;; set the doc here because in early-thread FDOCUMENTATION is not
101 (setf (fdocumentation '*current-thread* 'variable)
102 "Bound in each thread to the thread itself.")
104 (defstruct (thread (:constructor %make-thread))
106 "Thread type. Do not rely on threads being structs as it may change
112 (interruptions-lock (make-mutex :name "thread interruptions lock"))
114 (result-lock (make-mutex :name "thread result lock")))
118 (fdocumentation 'thread-name 'function)
119 "Name of the thread. Can be assigned to using SETF. Thread names can be
120 arbitrary printable objects, and need not be unique.")
122 (def!method print-object ((thread thread) stream)
123 (print-unreadable-object (thread stream :type t :identity t)
124 (let* ((cookie (list thread))
125 (info (if (thread-alive-p thread)
128 (join-thread thread :default cookie))))
129 (state (if (eq :running info)
131 (if (eq cookie (car info))
134 (values (when (eq :finished state) info)))
136 "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
142 (defun thread-alive-p (thread)
144 "Return T if THREAD is still alive. Note that the return value is
145 potentially stale even before the function returns, as the thread may exit at
147 (thread-%alive-p thread))
149 ;; A thread is eligible for gc iff it has finished and there are no
150 ;; more references to it. This list is supposed to keep a reference to
151 ;; all running threads.
152 (defvar *all-threads* ())
153 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
155 (defvar *default-alloc-signal* nil)
157 (defmacro with-all-threads-lock (&body body)
158 `(with-system-mutex (*all-threads-lock*)
161 (defun list-all-threads ()
163 "Return a list of the live threads. Note that the return value is
164 potentially stale even before the function returns, as new threads may be
165 created and old ones may exit at any time."
166 (with-all-threads-lock
167 (copy-list *all-threads*)))
169 (declaim (inline current-thread-sap))
170 (defun current-thread-sap ()
171 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
173 (declaim (inline current-thread-os-thread))
174 (defun current-thread-os-thread ()
176 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
180 (defun init-initial-thread ()
181 (/show0 "Entering INIT-INITIAL-THREAD")
182 (let ((initial-thread (%make-thread :name "initial thread"
184 :os-thread (current-thread-os-thread))))
185 (setq *current-thread* initial-thread)
186 ;; Either *all-threads* is empty or it contains exactly one thread
187 ;; in case we are in reinit since saving core with multiple
188 ;; threads doesn't work.
189 (setq *all-threads* (list initial-thread))))
192 ;;;; Aliens, low level stuff
194 (define-alien-routine "kill_safely"
196 (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
201 ;; FIXME it would be good to define what a thread id is or isn't
202 ;; (our current assumption is that it's a fixnum). It so happens
203 ;; that on Linux it's a pid, but it might not be on posix thread
205 (define-alien-routine ("create_thread" %create-thread)
206 unsigned-long (lisp-fun-address unsigned-long))
208 (declaim (inline %block-deferrable-signals))
209 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
211 (where sb!alien:unsigned-long)
212 (old sb!alien:unsigned-long))
214 (defun block-deferrable-signals ()
215 (%block-deferrable-signals 0 0))
219 (declaim (inline %lutex-init %lutex-wait %lutex-wake
220 %lutex-lock %lutex-unlock))
222 (define-alien-routine ("lutex_init" %lutex-init)
223 int (lutex unsigned-long))
225 (define-alien-routine ("lutex_wait" %lutex-wait)
226 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
228 (define-alien-routine ("lutex_wake" %lutex-wake)
229 int (lutex unsigned-long) (n int))
231 (define-alien-routine ("lutex_lock" %lutex-lock)
232 int (lutex unsigned-long))
234 (define-alien-routine ("lutex_trylock" %lutex-trylock)
235 int (lutex unsigned-long))
237 (define-alien-routine ("lutex_unlock" %lutex-unlock)
238 int (lutex unsigned-long))
240 (define-alien-routine ("lutex_destroy" %lutex-destroy)
241 int (lutex unsigned-long))
243 ;; FIXME: Defining a whole bunch of alien-type machinery just for
244 ;; passing primitive lutex objects directly to foreign functions
245 ;; doesn't seem like fun right now. So instead we just manually
246 ;; pin the lutex, get its address, and let the callee untag it.
247 (defmacro with-lutex-address ((name lutex) &body body)
248 `(let ((,name ,lutex))
249 (with-pinned-objects (,name)
250 (let ((,name (get-lisp-obj-address ,name)))
254 (/show0 "Entering MAKE-LUTEX")
255 ;; Suppress GC until the lutex has been properly registered with
258 (let ((lutex (sb!vm::%make-lutex)))
261 (with-lutex-address (lutex lutex)
267 (declaim (inline futex-wait %futex-wait futex-wake))
269 (define-alien-routine ("futex_wait" %futex-wait)
270 int (word unsigned-long) (old-value unsigned-long)
271 (to-sec long) (to-usec unsigned-long))
273 (defun futex-wait (word old to-sec to-usec)
275 (%futex-wait word old to-sec to-usec)))
277 (define-alien-routine "futex_wake"
278 int (word unsigned-long) (n unsigned-long))))
280 ;;; used by debug-int.lisp to access interrupt contexts
281 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
283 (defun sb!vm::current-thread-offset-sap (n)
284 (declare (type (unsigned-byte 27) n))
285 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
286 (* n sb!vm:n-word-bytes)))
289 (defun sb!vm::current-thread-offset-sap (n)
290 (declare (type (unsigned-byte 27) n))
291 (sb!vm::current-thread-offset-sap n))
296 (declaim (inline get-spinlock release-spinlock))
298 ;;; Should always be called with interrupts disabled.
299 (defun get-spinlock (spinlock)
300 (declare (optimize (speed 3) (safety 0)))
301 (let* ((new *current-thread*)
302 (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
305 (error "Recursive lock attempt on ~S." spinlock))
308 (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
310 (return-from get-spinlock t))))
311 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
312 ;; If interrupts are disabled, but we are allowed to
313 ;; enabled them, check for pending interrupts every once
314 ;; in a while. %CHECK-INTERRUPTS is taking shortcuts, make
315 ;; sure that deferrables are unblocked by doing an empty
316 ;; WITH-INTERRUPTS once.
320 (loop repeat 128 do (cas)) ; 128 is arbitrary here
321 (sb!unix::%check-interrupts)))
325 (defun release-spinlock (spinlock)
326 (declare (optimize (speed 3) (safety 0)))
327 ;; On x86 and x86-64 we can get away with no memory barriers, (see
328 ;; Linux kernel mailing list "spin_unlock optimization(i386)"
329 ;; thread, summary at
330 ;; http://kt.iserv.nl/kernel-traffic/kt19991220_47.html#1.
332 ;; If the compiler may reorder this with other instructions, insert
333 ;; compiler barrier here.
335 ;; FIXME: this does not work on SMP Pentium Pro and OOSTORE systems,
336 ;; neither on most non-x86 architectures (but we don't have threads
338 (setf (spinlock-value spinlock) nil))
344 (setf (fdocumentation 'make-mutex 'function)
346 (fdocumentation 'mutex-name 'function)
347 "The name of the mutex. Setfable.")
349 #!+(and sb-thread (not sb-lutex))
351 (define-structure-slot-addressor mutex-state-address
354 ;; Important: current code assumes these are fixnums or other
355 ;; lisp objects that don't need pinning.
356 (defconstant +lock-free+ 0)
357 (defconstant +lock-taken+ 1)
358 (defconstant +lock-contested+ 2))
360 (defun mutex-owner (mutex)
361 "Current owner of the mutex, NIL if the mutex is free. Naturally,
362 this is racy by design (another thread may acquire the mutex after
363 this function returns), it is intended for informative purposes. For
364 testing whether the current thread is holding a mutex see
366 ;; Make sure to get the current value.
367 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
369 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
371 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
372 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
373 non-NIL and the mutex is in use, sleep until it is available.
375 Note: using GET-MUTEX to assign a MUTEX to another thread then the
376 current one is not recommended, and liable to be deprecated.
378 GET-MUTEX is not interrupt safe. The correct way to call it is:
382 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
385 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
386 call while the mutex is in an inconsistent state while
387 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
389 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
391 (declare (type mutex mutex) (optimize (speed 3))
392 #!-sb-thread (ignore waitp))
394 (setq new-owner *current-thread*))
395 (let ((old (mutex-%owner mutex)))
396 (when (eq new-owner old)
397 (error "Recursive lock attempt ~S." mutex))
400 (error "Strange deadlock on ~S in an unithreaded build?" mutex)))
402 (setf (mutex-%owner mutex) new-owner)
405 ;; FIXME: Lutexes do not currently support deadlines, as at least
406 ;; on Darwin pthread_foo_timedbar functions are not supported:
407 ;; this means that we probably need to use the Carbon multiprocessing
408 ;; functions on Darwin.
410 ;; FIXME: This is definitely not interrupt safe: what happens if
411 ;; we get hit (1) during the lutex calls (ok, they may be safe,
412 ;; but has that been checked?) (2) after the lutex call, but
413 ;; before setting the mutex owner.
415 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
417 (with-interrupts (%lutex-lock lutex))
418 (%lutex-trylock lutex))))
419 (setf (mutex-%owner mutex) new-owner)
422 ;; This is a direct translation of the Mutex 2 algorithm from
423 ;; "Futexes are Tricky" by Ulrich Drepper.
424 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
427 (unless (or (eql +lock-free+ old) (not waitp))
430 (when (or (eql +lock-contested+ old)
431 (not (eql +lock-free+
432 (sb!ext:compare-and-swap (mutex-state mutex)
435 ;; Wait on the contested lock.
437 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
438 (case (with-pinned-objects (mutex)
439 (futex-wait (mutex-state-address mutex)
440 (get-lisp-obj-address +lock-contested+)
443 ((1) (signal-deadline))
445 (otherwise (return))))))
446 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
450 (unless (eql +lock-free+ old)
452 (cond ((eql +lock-free+ old)
453 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
456 (bug "Old owner in free mutex: ~S" prev))
459 (bug "Failed to acquire lock with WAITP."))))))
461 (defun release-mutex (mutex &key (if-not-owner :punt))
463 "Release MUTEX by setting it to NIL. Wake up threads waiting for
466 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
469 If the current thread is not the owner of the mutex then it silently
470 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
471 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
472 IF-NOT-OWNER is :FORCE)."
473 (declare (type mutex mutex))
474 ;; Order matters: set owner to NIL before releasing state.
475 (let* ((self *current-thread*)
476 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
477 (unless (eql self old-owner)
479 ((:punt) (return-from release-mutex nil))
481 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
485 (setf (mutex-%owner mutex) nil)
487 (with-lutex-address (lutex (mutex-lutex mutex))
488 (%lutex-unlock lutex))
490 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
491 ;; unsigned-byte type this can be used:
493 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
494 ;; (unless (eql old +lock-free+)
495 ;; (setf (mutex-state mutex) +lock-free+)
496 ;; (with-pinned-objects (mutex)
497 ;; (futex-wake (mutex-state-address mutex) 1))))
498 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
499 +lock-taken+ +lock-free+)))
500 (when (eql old +lock-contested+)
501 (sb!ext:compare-and-swap (mutex-state mutex)
502 +lock-contested+ +lock-free+)
503 (with-pinned-objects (mutex)
504 (futex-wake (mutex-state-address mutex) 1))))
508 ;;;; Waitqueues/condition variables
510 (defstruct (waitqueue (:constructor %make-waitqueue))
513 (name nil :type (or null simple-string))
514 #!+(and sb-lutex sb-thread)
519 (defun make-waitqueue (&key name)
521 "Create a waitqueue."
522 (%make-waitqueue :name name))
525 (setf (fdocumentation 'waitqueue-name 'function)
526 "The name of the waitqueue. Setfable.")
528 #!+(and sb-thread (not sb-lutex))
529 (define-structure-slot-addressor waitqueue-data-address
533 (defun condition-wait (queue mutex)
535 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
536 thread may subsequently notify us using CONDITION-NOTIFY, at which
537 time we reacquire MUTEX and return to the caller."
538 #!-sb-thread (declare (ignore queue))
540 #!-sb-thread (error "Not supported in unithread builds.")
542 (let ((me *current-thread*))
543 (assert (eq me (mutex-%owner mutex)))
544 (/show0 "CONDITION-WAITing")
546 ;; Need to disable interrupts so that we don't miss setting the
547 ;; owner on our way out. (pthread_cond_wait handles the actual
552 (setf (mutex-%owner mutex) nil)
553 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
554 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
555 (with-local-interrupts
556 (%lutex-wait queue-lutex-address mutex-lutex-address)))))
557 (setf (mutex-%owner mutex) me)))
559 ;; Need to disable interrupts so that we don't miss grabbing the
560 ;; mutex on our way out.
563 ;; This setf becomes visible to other CPUS due to the usual
564 ;; memory barrier semantics of lock acquire/release. This must
565 ;; not be moved into the loop else wakeups may be lost upon
566 ;; continuing after a deadline or EINTR.
567 (setf (waitqueue-data queue) me)
569 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
570 (case (unwind-protect
571 (with-pinned-objects (queue me)
572 ;; RELEASE-MUTEX is purposefully as close to
573 ;; FUTEX-WAIT as possible to reduce the size
574 ;; of the window where WAITQUEUE-DATA may be
575 ;; set by a notifier.
576 (release-mutex mutex)
577 ;; Now we go to sleep using futex-wait. If
578 ;; anyone else manages to grab MUTEX and call
579 ;; CONDITION-NOTIFY during this comment, it
580 ;; will change queue->data, and so futex-wait
581 ;; returns immediately instead of sleeping.
582 ;; Ergo, no lost wakeup. We may get spurious
583 ;; wakeups, but that's ok.
584 (allow-with-interrupts
585 (futex-wait (waitqueue-data-address queue)
586 (get-lisp-obj-address me)
587 ;; our way if saying "no
591 ;; If we are interrupted while waiting, we should
592 ;; do these things before returning. Ideally, in
593 ;; the case of an unhandled signal, we should do
594 ;; them before entering the debugger, but this is
595 ;; better than nothing.
596 (allow-with-interrupts (get-mutex mutex)))
598 ((1) (signal-deadline))
601 ;; EWOULDBLOCK, -1 here, is the possible spurious wakeup
602 ;; case. 0 is the normal wakeup.
603 (otherwise (return)))))))))
605 (defun condition-notify (queue &optional (n 1))
607 "Notify N threads waiting on QUEUE. The same mutex that is used in
608 the corresponding CONDITION-WAIT must be held by this thread during
610 #!-sb-thread (declare (ignore queue n))
611 #!-sb-thread (error "Not supported in unithread builds.")
613 (declare (type (and fixnum (integer 1)) n))
614 (/show0 "Entering CONDITION-NOTIFY")
618 (with-lutex-address (lutex (waitqueue-lutex queue))
619 (%lutex-wake lutex n))
620 ;; no problem if >1 thread notifies during the comment in
621 ;; condition-wait: as long as the value in queue-data isn't the
622 ;; waiting thread's id, it matters not what it is
623 ;; XXX we should do something to ensure that the result of this setf
624 ;; is visible to all CPUs
626 (let ((me *current-thread*))
628 (setf (waitqueue-data queue) me)
629 (with-pinned-objects (queue)
630 (futex-wake (waitqueue-data-address queue) n))))))
632 (defun condition-broadcast (queue)
634 "Notify all threads waiting on QUEUE."
635 (condition-notify queue
636 ;; On a 64-bit platform truncating M-P-F to an int
637 ;; results in -1, which wakes up only one thread.
639 most-positive-fixnum)))
644 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
646 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
647 should be considered an implementation detail, and may change in the
649 (name nil :type (or null simple-string))
650 (%count 0 :type (integer 0))
651 (waitcount 0 :type (integer 0))
653 (queue (make-waitqueue)))
655 (setf (fdocumentation 'semaphore-name 'function)
656 "The name of the semaphore INSTANCE. Setfable.")
658 (declaim (inline semaphore-count))
659 (defun semaphore-count (instance)
660 "Returns the current count of the semaphore INSTANCE."
661 (semaphore-%count instance))
663 (defun make-semaphore (&key name (count 0))
665 "Create a semaphore with the supplied COUNT and NAME."
666 (%make-semaphore name count))
668 (defun wait-on-semaphore (semaphore)
670 "Decrement the count of SEMAPHORE if the count would not be
671 negative. Else blocks until the semaphore can be decremented."
672 ;; A more direct implementation based directly on futexes should be
675 ;; We need to disable interrupts so that we don't forget to
676 ;; decrement the waitcount (which would happen if an asynch
677 ;; interrupt should catch us on our way out from the loop.)
678 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
679 ;; Quick check: is it positive? If not, enter the wait loop.
680 (let ((count (semaphore-%count semaphore)))
682 (setf (semaphore-%count semaphore) (1- count))
685 (incf (semaphore-waitcount semaphore))
686 (loop until (plusp (setf count (semaphore-%count semaphore)))
687 do (condition-wait (semaphore-queue semaphore)
688 (semaphore-mutex semaphore)))
689 (setf (semaphore-%count semaphore) (1- count)))
690 (decf (semaphore-waitcount semaphore)))))))
692 (defun signal-semaphore (semaphore &optional (n 1))
694 "Increment the count of SEMAPHORE by N. If there are threads waiting
695 on this semaphore, then N of them is woken up."
696 (declare (type (integer 1) n))
697 ;; Need to disable interrupts so that we don't lose a wakeup after
698 ;; we have incremented the count.
699 (with-system-mutex ((semaphore-mutex semaphore))
700 (let ((waitcount (semaphore-waitcount semaphore))
701 (count (incf (semaphore-%count semaphore) n)))
702 (when (plusp waitcount)
703 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
706 ;;;; Job control, independent listeners
709 (lock (make-mutex :name "session lock"))
711 (interactive-threads nil)
712 (interactive-threads-queue (make-waitqueue)))
714 (defvar *session* nil)
716 ;;; The debugger itself tries to acquire the session lock, don't let
717 ;;; funny situations (like getting a sigint while holding the session
718 ;;; lock) occur. At the same time we need to allow interrupts while
719 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
720 ;;; be interruptible.
722 ;;; Take care: we sometimes need to obtain the session lock while
723 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
724 ;;; _after_ getting a session lock! (Deadlock risk.)
726 ;;; FIXME: It would be good to have ordered locks to ensure invariants
728 (defmacro with-session-lock ((session) &body body)
729 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
732 (defun new-session ()
733 (make-session :threads (list *current-thread*)
734 :interactive-threads (list *current-thread*)))
736 (defun init-job-control ()
737 (/show0 "Entering INIT-JOB-CONTROL")
738 (setf *session* (new-session))
739 (/show0 "Exiting INIT-JOB-CONTROL"))
741 (defun %delete-thread-from-session (thread session)
742 (with-session-lock (session)
743 (setf (session-threads session)
744 (delete thread (session-threads session))
745 (session-interactive-threads session)
746 (delete thread (session-interactive-threads session)))))
748 (defun call-with-new-session (fn)
749 (%delete-thread-from-session *current-thread* *session*)
750 (let ((*session* (new-session)))
753 (defmacro with-new-session (args &body forms)
754 (declare (ignore args)) ;for extensibility
755 (sb!int:with-unique-names (fb-name)
756 `(labels ((,fb-name () ,@forms))
757 (call-with-new-session (function ,fb-name)))))
759 ;;; Remove thread from its session, if it has one.
761 (defun handle-thread-exit (thread)
762 (/show0 "HANDLING THREAD EXIT")
764 (with-all-threads-lock
765 (setf (thread-%alive-p thread) nil)
766 (setf (thread-os-thread thread) nil)
767 (setq *all-threads* (delete thread *all-threads*))
769 (%delete-thread-from-session thread *session*)))
772 (/show0 "FREEING MUTEX LUTEX")
773 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
774 (%lutex-destroy lutex))))
776 (defun terminate-session ()
778 "Kill all threads in session except for this one. Does nothing if current
779 thread is not the foreground thread."
780 ;; FIXME: threads created in other threads may escape termination
782 (with-session-lock (*session*)
783 (and (eq *current-thread*
784 (car (session-interactive-threads *session*)))
785 (session-threads *session*)))))
786 ;; do the kill after dropping the mutex; unwind forms in dying
787 ;; threads may want to do session things
788 (dolist (thread to-kill)
789 (unless (eq thread *current-thread*)
790 ;; terminate the thread but don't be surprised if it has
791 ;; exited in the meantime
792 (handler-case (terminate-thread thread)
793 (interrupt-thread-error ()))))))
795 ;;; called from top of invoke-debugger
796 (defun debugger-wait-until-foreground-thread (stream)
797 "Returns T if thread had been running in background, NIL if it was
799 (declare (ignore stream))
803 (with-session-lock (*session*)
804 (not (member *current-thread*
805 (session-interactive-threads *session*))))
808 (defun get-foreground ()
811 (let ((was-foreground t))
813 (/show0 "Looping in GET-FOREGROUND")
814 (with-session-lock (*session*)
815 (let ((int-t (session-interactive-threads *session*)))
816 (when (eq (car int-t) *current-thread*)
817 (unless was-foreground
818 (format *query-io* "Resuming thread ~A~%" *current-thread*))
819 (return-from get-foreground t))
820 (setf was-foreground nil)
821 (unless (member *current-thread* int-t)
822 (setf (cdr (last int-t))
823 (list *current-thread*)))
825 (session-interactive-threads-queue *session*)
826 (session-lock *session*)))))))
828 (defun release-foreground (&optional next)
830 "Background this thread. If NEXT is supplied, arrange for it to
831 have the foreground next."
832 #!-sb-thread (declare (ignore next))
835 (with-session-lock (*session*)
836 (when (rest (session-interactive-threads *session*))
837 (setf (session-interactive-threads *session*)
838 (delete *current-thread* (session-interactive-threads *session*))))
840 (setf (session-interactive-threads *session*)
842 (delete next (session-interactive-threads *session*)))))
843 (condition-broadcast (session-interactive-threads-queue *session*))))
845 (defun foreground-thread ()
846 (car (session-interactive-threads *session*)))
848 (defun make-listener-thread (tty-name)
849 (assert (probe-file tty-name))
850 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
851 (out (sb!unix:unix-dup in))
852 (err (sb!unix:unix-dup in)))
853 (labels ((thread-repl ()
854 (sb!unix::unix-setsid)
855 (let* ((sb!impl::*stdin*
856 (make-fd-stream in :input t :buffering :line
859 (make-fd-stream out :output t :buffering :line
862 (make-fd-stream err :output t :buffering :line
865 (make-fd-stream err :input t :output t
868 (sb!impl::*descriptor-handlers* nil))
871 (sb!impl::toplevel-repl nil)
872 (sb!int:flush-standard-output-streams))))))
873 (make-thread #'thread-repl))))
878 (defun make-thread (function &key name)
880 "Create a new thread of NAME that runs FUNCTION. When the function
881 returns the thread exits. The return values of FUNCTION are kept
882 around and can be retrieved by JOIN-THREAD."
883 #!-sb-thread (declare (ignore function name))
884 #!-sb-thread (error "Not supported in unithread builds.")
886 (let* ((thread (%make-thread :name name))
887 (setup-sem (make-semaphore :name "Thread setup semaphore"))
888 (real-function (coerce function 'function))
891 ;; In time we'll move some of the binding presently done in C
894 ;; KLUDGE: Here we have a magic list of variables that are
895 ;; not thread-safe for one reason or another. As people
896 ;; report problems with the thread safety of certain
897 ;; variables, (e.g. "*print-case* in multiple threads
898 ;; broken", sbcl-devel 2006-07-14), we add a few more
899 ;; bindings here. The Right Thing is probably some variant
900 ;; of Allegro's *cl-default-special-bindings*, as that is at
901 ;; least accessible to users to secure their own libraries.
904 ;; As it is, this lambda must not cons until we are ready
905 ;; to run GC. Be very careful.
906 (let* ((*current-thread* thread)
907 (*restart-clusters* nil)
908 (*handler-clusters* (sb!kernel::initial-handler-clusters))
909 (*condition-restarts* nil)
910 (sb!impl::*deadline* nil)
911 (sb!impl::*step-out* nil)
912 ;; internal printer variables
913 (sb!impl::*previous-case* nil)
914 (sb!impl::*previous-readtable-case* nil)
916 (sb!impl::*merge-sort-temp-vector* empty)
917 (sb!impl::*zap-array-data-temp* empty)
918 (sb!impl::*internal-symbol-output-fun* nil)
919 (sb!impl::*descriptor-handlers* nil)) ; serve-event
921 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
922 (setf (thread-os-thread thread) (current-thread-os-thread))
923 (with-mutex ((thread-result-lock thread))
924 (with-all-threads-lock
925 (push thread *all-threads*))
926 (with-session-lock (*session*)
927 (push thread (session-threads *session*)))
928 (setf (thread-%alive-p thread) t)
929 (signal-semaphore setup-sem)
930 ;; can't use handling-end-of-the-world, because that flushes
931 ;; output streams, and we don't necessarily have any (or we
932 ;; could be sharing them)
933 (catch 'sb!impl::toplevel-catcher
934 (catch 'sb!impl::%end-of-the-world
938 "~~@<Terminate this thread (~A)~~@:>"
942 (with-local-interrupts
943 ;; Now that most things have a chance
944 ;; to work properly without messing up
945 ;; other threads, it's time to enable
947 (sb!unix::unblock-deferrable-signals)
948 (setf (thread-result thread)
951 (funcall real-function))))
952 ;; Try to block deferrables. An
953 ;; interrupt may unwind it, but for a
954 ;; normal exit it prevents interrupt
956 (block-deferrable-signals))
957 ;; We're going down, can't handle interrupts
958 ;; sanely anymore. GC remains enabled.
959 (block-deferrable-signals)
960 ;; We don't want to run interrupts in a dead
961 ;; thread when we leave WITHOUT-INTERRUPTS.
962 ;; This potentially causes important
963 ;; interupts to be lost: SIGINT comes to
965 (setq *interrupt-pending* nil)
966 (handle-thread-exit thread))))))))
968 ;; If the starting thread is stopped for gc before it signals the
969 ;; semaphore then we'd be stuck.
970 (assert (not *gc-inhibit*))
971 ;; Keep INITIAL-FUNCTION pinned until the child thread is
972 ;; initialized properly. Wrap the whole thing in
973 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
976 (with-pinned-objects (initial-function)
979 (get-lisp-obj-address initial-function))))
980 (when (zerop os-thread)
981 (error "Can't create a new thread"))
982 (wait-on-semaphore setup-sem)
985 (defun join-thread (thread &key (default nil defaultp))
987 "Suspend current thread until THREAD exits. Returns the result
988 values of the thread function. If the thread does not exit normally,
989 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
990 (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
991 (cond ((car (thread-result thread))
992 (return-from join-thread
993 (values-list (cdr (thread-result thread)))))
995 (return-from join-thread default))))
996 (error 'join-thread-error :thread thread))
998 (defun destroy-thread (thread)
1000 "Deprecated. Same as TERMINATE-THREAD."
1001 (terminate-thread thread))
1003 (defmacro with-interruptions-lock ((thread) &body body)
1004 `(with-system-mutex ((thread-interruptions-lock ,thread))
1007 ;;; Called from the signal handler.
1009 (defun run-interruption ()
1010 (let ((interruption (with-interruptions-lock (*current-thread*)
1011 (pop (thread-interruptions *current-thread*)))))
1012 ;; If there is more to do, then resignal and let the normal
1013 ;; interrupt deferral mechanism take care of the rest. From the
1014 ;; OS's point of view the signal we are in the handler for is no
1015 ;; longer pending, so the signal will not be lost.
1016 (when (thread-interruptions *current-thread*)
1017 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1019 (funcall interruption))))
1021 (defun interrupt-thread (thread function)
1023 "Interrupt the live THREAD and make it run FUNCTION. A moderate
1024 degree of care is expected for use of INTERRUPT-THREAD, due to its
1025 nature: if you interrupt a thread that was holding important locks
1026 then do something that turns out to need those locks, you probably
1027 won't like the effect. FUNCTION runs with interrupts disabled, but
1028 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1029 enable interrupts (GET-MUTEX when contended, for instance) so the
1030 first thing to do is usually a WITH-INTERRUPTS or a
1031 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1032 run in same the order they were sent."
1034 (declare (ignore thread))
1036 (with-interrupt-bindings
1037 (with-interrupts (funcall function)))
1039 (let ((os-thread (thread-os-thread thread)))
1040 (cond ((not os-thread)
1041 (error 'interrupt-thread-error :thread thread))
1043 (with-interruptions-lock (thread)
1044 ;; Append to the end of the interruptions queue. It's
1045 ;; O(N), but it does not hurt to slow interruptors down a
1046 ;; bit when the queue gets long.
1047 (setf (thread-interruptions thread)
1048 (append (thread-interruptions thread)
1051 (allow-with-interrupts
1052 (funcall function))))))))
1053 (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1054 (error 'interrupt-thread-error :thread thread))))))
1056 (defun terminate-thread (thread)
1058 "Terminate the thread identified by THREAD, by causing it to run
1059 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1060 (interrupt-thread thread 'sb!ext:quit))
1062 (define-alien-routine "thread_yield" int)
1065 (setf (fdocumentation 'thread-yield 'function)
1066 "Yield the processor to other threads.")
1068 ;;; internal use only. If you think you need to use these, either you
1069 ;;; are an SBCL developer, are doing something that you should discuss
1070 ;;; with an SBCL developer first, or are doing something that you
1071 ;;; should probably discuss with a professional psychiatrist first
1074 (defun %thread-sap (thread)
1075 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1076 (target (thread-os-thread thread)))
1078 (when (sap= thread-sap (int-sap 0)) (return nil))
1079 (let ((os-thread (sap-ref-word thread-sap
1080 (* sb!vm:n-word-bytes
1081 sb!vm::thread-os-thread-slot))))
1082 (when (= os-thread target) (return thread-sap))
1084 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1085 sb!vm::thread-next-slot)))))))
1087 (defun %symbol-value-in-thread (symbol thread)
1088 ;; Prevent the thread from dying completely while we look for the TLS
1090 (with-all-threads-lock
1091 (if (thread-alive-p thread)
1092 (let* ((offset (* sb!vm:n-word-bytes
1093 (sb!vm::symbol-tls-index symbol)))
1094 (tl-val (sap-ref-word (%thread-sap thread) offset)))
1095 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
1096 (values nil :unbound)
1097 (values (make-lisp-obj tl-val) :bound)))
1098 (values nil :dead))))
1100 (defun %set-symbol-value-in-thread (symbol thread value)
1101 (with-pinned-objects (value)
1102 ;; Prevent the thread from dying completely while we look for the TLS
1104 (with-all-threads-lock
1105 (if (thread-alive-p thread)
1106 (let* ((offset (* sb!vm:n-word-bytes
1107 (sb!vm::symbol-tls-index symbol)))
1108 (sap (%thread-sap thread))
1109 (tl-val (sap-ref-word sap offset)))
1110 (cond ((eql tl-val sb!vm::no-tls-value-marker-widetag)
1111 (values nil :unbound))
1113 (setf (sap-ref-word sap offset)
1114 (get-lisp-obj-address value))
1115 (values value :bound))))
1116 (values nil :dead))))))
1118 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1119 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1122 If the value cannot be retrieved (because the thread has exited or because it
1123 has no local binding for NAME) and ERRORP is true signals an error of type
1124 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1125 NIL, and a secondary value of NIL.
1127 Can also be used with SETF to change the thread-local value of SYMBOL.
1129 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1130 mechanism form inter-thread communication."
1131 (declare (symbol symbol) (thread thread))
1133 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1134 (if (eq :bound status)
1137 (error 'symbol-value-in-thread-error
1140 :info (list :read status))
1144 (values (symbol-value symbol) t)
1146 (error 'symbol-value-in-thread-error
1149 :info (list :read :unbound))
1152 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1153 (declare (symbol symbol) (thread thread))
1155 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1156 (if (eq :bound status)
1159 (error 'symbol-value-in-thread-error
1162 :info (list :write status))
1166 (values (setf (symbol-value symbol) value) t)
1168 (error 'symbol-value-in-thread-error
1171 :info (list :write :unbound))
1174 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1175 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1180 (defun thread-stepping ()
1182 (sap-ref-word (current-thread-sap)
1183 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1185 (defun (setf thread-stepping) (value)
1186 (setf (sap-ref-word (current-thread-sap)
1187 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1188 (get-lisp-obj-address value)))