+ #!+sb-doc
+ "Background this thread. If NEXT is supplied, arrange for it to
+have the foreground next."
+ #!-sb-thread (declare (ignore next))
+ #!-sb-thread nil
+ #!+sb-thread
+ (with-session-lock (*session*)
+ (when (rest (session-interactive-threads *session*))
+ (setf (session-interactive-threads *session*)
+ (delete *current-thread* (session-interactive-threads *session*))))
+ (when next
+ (setf (session-interactive-threads *session*)
+ (list* next
+ (delete next (session-interactive-threads *session*)))))
+ (condition-broadcast (session-interactive-threads-queue *session*))))
+
+(defun foreground-thread ()
+ (car (session-interactive-threads *session*)))
+
+(defun make-listener-thread (tty-name)
+ (assert (probe-file tty-name))
+ (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
+ (out (sb!unix:unix-dup in))
+ (err (sb!unix:unix-dup in)))
+ (labels ((thread-repl ()
+ (sb!unix::unix-setsid)
+ (let* ((sb!impl::*stdin*
+ (make-fd-stream in :input t :buffering :line
+ :dual-channel-p t))
+ (sb!impl::*stdout*
+ (make-fd-stream out :output t :buffering :line
+ :dual-channel-p t))
+ (sb!impl::*stderr*
+ (make-fd-stream err :output t :buffering :line
+ :dual-channel-p t))
+ (sb!impl::*tty*
+ (make-fd-stream err :input t :output t
+ :buffering :line
+ :dual-channel-p t))
+ (sb!impl::*descriptor-handlers* nil))
+ (with-new-session ()
+ (unwind-protect
+ (sb!impl::toplevel-repl nil)
+ (sb!int:flush-standard-output-streams))))))
+ (make-thread #'thread-repl))))
+\f
+
+;;;; The beef
+
+(defun make-thread (function &key name arguments)
+ #!+sb-doc
+ "Create a new thread of NAME that runs FUNCTION with the argument
+list designator provided (defaults to no argument). When the function
+returns the thread exits. The return values of FUNCTION are kept
+around and can be retrieved by JOIN-THREAD."
+ #!-sb-thread (declare (ignore function name arguments))
+ #!-sb-thread (error "Not supported in unithread builds.")
+ #!+sb-thread (assert (or (atom arguments)
+ (null (cdr (last arguments))))
+ (arguments)
+ "Argument passed to ~S, ~S, is an improper list."
+ 'make-thread arguments)
+ #!+sb-thread
+ (let* ((thread (%make-thread :name name))
+ (setup-sem (make-semaphore :name "Thread setup semaphore"))
+ (real-function (coerce function 'function))
+ (arguments (if (listp arguments)
+ arguments
+ (list arguments)))
+ (initial-function
+ (named-lambda initial-thread-function ()
+ ;; In time we'll move some of the binding presently done in C
+ ;; here too.
+ ;;
+ ;; KLUDGE: Here we have a magic list of variables that are
+ ;; not thread-safe for one reason or another. As people
+ ;; report problems with the thread safety of certain
+ ;; variables, (e.g. "*print-case* in multiple threads
+ ;; broken", sbcl-devel 2006-07-14), we add a few more
+ ;; bindings here. The Right Thing is probably some variant
+ ;; of Allegro's *cl-default-special-bindings*, as that is at
+ ;; least accessible to users to secure their own libraries.
+ ;; --njf, 2006-07-15
+ ;;
+ ;; As it is, this lambda must not cons until we are ready
+ ;; to run GC. Be very careful.
+ (let* ((*current-thread* thread)
+ (*restart-clusters* nil)
+ (*handler-clusters* (sb!kernel::initial-handler-clusters))
+ (*condition-restarts* nil)
+ (sb!impl::*deadline* nil)
+ (sb!impl::*deadline-seconds* nil)
+ (sb!impl::*step-out* nil)
+ ;; internal printer variables
+ (sb!impl::*previous-case* nil)
+ (sb!impl::*previous-readtable-case* nil)
+ (sb!impl::*internal-symbol-output-fun* nil)
+ (sb!impl::*descriptor-handlers* nil)) ; serve-event
+ ;; Binding from C
+ (setf sb!vm:*alloc-signal* *default-alloc-signal*)
+ (setf (thread-os-thread thread) (current-thread-os-thread))
+ (with-mutex ((thread-result-lock thread))
+ (with-all-threads-lock
+ (push thread *all-threads*))
+ (with-session-lock (*session*)
+ (push thread (session-threads *session*)))
+ (setf (thread-%alive-p thread) t)
+ (signal-semaphore setup-sem)
+ ;; can't use handling-end-of-the-world, because that flushes
+ ;; output streams, and we don't necessarily have any (or we
+ ;; could be sharing them)
+ (catch 'sb!impl::toplevel-catcher
+ (catch 'sb!impl::%end-of-the-world
+ (with-simple-restart
+ (terminate-thread
+ (format nil
+ "~~@<Terminate this thread (~A)~~@:>"
+ *current-thread*))
+ (without-interrupts
+ (unwind-protect
+ (with-local-interrupts
+ ;; Now that most things have a chance
+ ;; to work properly without messing up
+ ;; other threads, it's time to enable
+ ;; signals.
+ (sb!unix::unblock-deferrable-signals)
+ (setf (thread-result thread)
+ (cons t
+ (multiple-value-list
+ (apply real-function arguments))))
+ ;; Try to block deferrables. An
+ ;; interrupt may unwind it, but for a
+ ;; normal exit it prevents interrupt
+ ;; loss.
+ (block-deferrable-signals))
+ ;; We're going down, can't handle interrupts
+ ;; sanely anymore. GC remains enabled.
+ (block-deferrable-signals)
+ ;; We don't want to run interrupts in a dead
+ ;; thread when we leave WITHOUT-INTERRUPTS.
+ ;; This potentially causes important
+ ;; interupts to be lost: SIGINT comes to
+ ;; mind.
+ (setq *interrupt-pending* nil)
+ (handle-thread-exit thread))))))))
+ (values))))
+ ;; If the starting thread is stopped for gc before it signals the
+ ;; semaphore then we'd be stuck.
+ (assert (not *gc-inhibit*))
+ ;; Keep INITIAL-FUNCTION pinned until the child thread is
+ ;; initialized properly. Wrap the whole thing in
+ ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
+ ;; thread.
+ (without-interrupts
+ (with-pinned-objects (initial-function)
+ (let ((os-thread
+ (%create-thread
+ (get-lisp-obj-address initial-function))))
+ (when (zerop os-thread)
+ (error "Can't create a new thread"))
+ (wait-on-semaphore setup-sem)
+ thread)))))
+
+(defun join-thread (thread &key (default nil defaultp) timeout)
+ #!+sb-doc
+ "Suspend current thread until THREAD exits. Return the result values of the
+thread function.
+
+If the thread does not exit normally within TIMEOUT seconds return DEFAULT if
+given, or else signal JOIN-THREAD-ERROR.
+
+NOTE: Return convention in case of a timeout is exprimental and subject to
+change."
+ (let ((lock (thread-result-lock thread))
+ (got-it nil)
+ (problem :timeout))
+ (without-interrupts
+ (unwind-protect
+ (if (setf got-it
+ (allow-with-interrupts
+ ;; Don't use the timeout if the thread is not alive anymore.
+ (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
+ (cond ((car (thread-result thread))
+ (return-from join-thread
+ (values-list (cdr (thread-result thread)))))
+ (defaultp
+ (return-from join-thread default))
+ (t
+ (setf problem :abort)))
+ (when defaultp
+ (return-from join-thread default)))
+ (when got-it
+ (release-mutex lock))))
+ (error 'join-thread-error :thread thread :problem problem)))
+
+(defun destroy-thread (thread)
+ #!+sb-doc
+ "Deprecated. Same as TERMINATE-THREAD."
+ (terminate-thread thread))
+
+(defmacro with-interruptions-lock ((thread) &body body)
+ `(with-system-mutex ((thread-interruptions-lock ,thread))
+ ,@body))
+
+;;; Called from the signal handler.
+#!-win32
+(defun run-interruption ()
+ (let ((interruption (with-interruptions-lock (*current-thread*)
+ (pop (thread-interruptions *current-thread*)))))
+ ;; If there is more to do, then resignal and let the normal
+ ;; interrupt deferral mechanism take care of the rest. From the
+ ;; OS's point of view the signal we are in the handler for is no
+ ;; longer pending, so the signal will not be lost.
+ (when (thread-interruptions *current-thread*)
+ (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
+ (when interruption
+ (funcall interruption))))
+
+(defun interrupt-thread (thread function)
+ #!+sb-doc
+ "Interrupt THREAD and make it run FUNCTION.
+
+The interrupt is asynchronous, and can occur anywhere with the exception of
+sections protected using SB-SYS:WITHOUT-INTERRUPTS.
+
+FUNCTION is called with interrupts disabled, under
+SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
+enable interrupts internally, in most cases FUNCTION should either enter
+SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
+SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
+
+When a thread receives multiple interrupts, they are executed in the order
+they were sent -- first in, first out.
+
+This means that a great degree of care is required to use INTERRUPT-THREAD
+safely and sanely in a production environment. The general recommendation is
+to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
+entirely from production environments -- it is simply exceedingly hard to use
+correctly.
+
+With those caveats in mind, what you need to know when using it:
+
+ * If calling FUNCTION causes a non-local transfer of control (ie. an
+ unwind), all normal cleanup forms will be executed.
+
+ However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
+ it is just as if that had happened due to a regular GO, THROW, or
+ RETURN-FROM: the interrupted cleanup form and those following it in the
+ same UNWIND-PROTECT do not get executed.
+
+ SBCL tries to keep its own internals asynch-unwind-safe, but this is
+ frankly an unreasonable expectation for third party libraries, especially
+ given that asynch-unwind-safety does not compose: a function calling
+ only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
+
+ This means that in order for an asych unwind to be safe, the entire
+ callstack at the point of interruption needs to be asynch-unwind-safe.
+
+ * In addition to asynch-unwind-safety you must consider the issue of
+ re-entrancy. INTERRUPT-THREAD can cause function that are never normally
+ called recursively to be re-entered during their dynamic contour,
+ which may cause them to misbehave. (Consider binding of special variables,
+ values of global variables, etc.)
+
+Take togather, these two restrict the \"safe\" things to do using
+INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
+interactive development use is using it to force entry to debugger to inspect
+the state of a thread:
+
+ (interrupt-thread thread #'break)
+
+Short version: be careful out there."
+ #!+win32
+ (declare (ignore thread))
+ #!+win32
+ (with-interrupt-bindings
+ (with-interrupts (funcall function)))
+ #!-win32
+ (let ((os-thread (thread-os-thread thread)))
+ (cond ((not os-thread)
+ (error 'interrupt-thread-error :thread thread))
+ (t
+ (with-interruptions-lock (thread)
+ ;; Append to the end of the interruptions queue. It's
+ ;; O(N), but it does not hurt to slow interruptors down a
+ ;; bit when the queue gets long.
+ (setf (thread-interruptions thread)
+ (append (thread-interruptions thread)
+ (list (lambda ()
+ (without-interrupts
+ (allow-with-interrupts
+ (funcall function))))))))
+ (when (minusp (kill-safely os-thread sb!unix:sigpipe))
+ (error 'interrupt-thread-error :thread thread))))))
+
+(defun terminate-thread (thread)
+ #!+sb-doc
+ "Terminate the thread identified by THREAD, by interrupting it and causing
+it to call SB-EXT:QUIT.
+
+The unwind caused by TERMINATE-THREAD is asynchronous, meaning that eg. thread
+executing
+
+ (let (foo)
+ (unwind-protect
+ (progn
+ (setf foo (get-foo))
+ (work-on-foo foo))
+ (when foo
+ ;; An interrupt occurring inside the cleanup clause
+ ;; will cause cleanups from the current UNWIND-PROTECT
+ ;; to be dropped.
+ (release-foo foo))))
+
+might miss calling RELEASE-FOO despite GET-FOO having returned true if the
+interrupt occurs inside the cleanup clause, eg. during execution of
+RELEASE-FOO.
+
+Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need to use
+WITHOUT-INTERRUPTS:
+
+ (let (foo)
+ (sb-sys:without-interrupts
+ (unwind-protect
+ (progn
+ (setf foo (sb-sys:allow-with-interrupts
+ (get-foo)))
+ (sb-sys:with-local-interrupts
+ (work-on-foo foo)))
+ (when foo
+ (release-foo foo)))))
+
+Since most libraries using UNWIND-PROTECT do not do this, you should never
+assume that unknown code can safely be terminated using TERMINATE-THREAD."
+ (interrupt-thread thread 'sb!ext:quit))
+
+(define-alien-routine "thread_yield" int)
+
+#!+sb-doc
+(setf (fdocumentation 'thread-yield 'function)
+ "Yield the processor to other threads.")
+
+;;; internal use only. If you think you need to use these, either you
+;;; are an SBCL developer, are doing something that you should discuss
+;;; with an SBCL developer first, or are doing something that you
+;;; should probably discuss with a professional psychiatrist first
+#!+sb-thread
+(progn
+ (defun %thread-sap (thread)
+ (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
+ (target (thread-os-thread thread)))
+ (loop
+ (when (sap= thread-sap (int-sap 0)) (return nil))
+ (let ((os-thread (sap-ref-word thread-sap
+ (* sb!vm:n-word-bytes
+ sb!vm::thread-os-thread-slot))))
+ (when (= os-thread target) (return thread-sap))
+ (setf thread-sap
+ (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
+ sb!vm::thread-next-slot)))))))
+
+ (defun %symbol-value-in-thread (symbol thread)
+ ;; Prevent the thread from dying completely while we look for the TLS
+ ;; area...
+ (with-all-threads-lock
+ (loop
+ (if (thread-alive-p thread)
+ (let* ((offset (sb!kernel:get-lisp-obj-address
+ (sb!vm::symbol-tls-index symbol)))
+ (obj (sap-ref-lispobj (%thread-sap thread) offset))
+ (tl-val (sb!kernel:get-lisp-obj-address obj)))
+ (cond ((zerop offset)
+ (return (values nil :no-tls-value)))
+ ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
+ (eql tl-val sb!vm:unbound-marker-widetag))
+ (return (values nil :unbound-in-thread)))
+ (t
+ (return (values obj :ok)))))
+ (return (values nil :thread-dead))))))
+
+ (defun %set-symbol-value-in-thread (symbol thread value)
+ (with-pinned-objects (value)
+ ;; Prevent the thread from dying completely while we look for the TLS
+ ;; area...
+ (with-all-threads-lock
+ (if (thread-alive-p thread)
+ (let ((offset (sb!kernel:get-lisp-obj-address
+ (sb!vm::symbol-tls-index symbol))))
+ (cond ((zerop offset)
+ (values nil :no-tls-value))
+ (t
+ (setf (sap-ref-lispobj (%thread-sap thread) offset)
+ value)
+ (values value :ok))))
+ (values nil :thread-dead)))))
+
+ (define-alien-variable tls-index-start unsigned-int)
+
+ ;; Get values from the TLS area of the current thread.
+ (defun %thread-local-references ()
+ (without-gcing
+ (let ((sap (%thread-sap *current-thread*)))
+ (loop for index from tls-index-start
+ below (symbol-value 'sb!vm::*free-tls-index*)
+ for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
+ for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
+ unless (or (not ok)
+ (typep obj '(or fixnum character))
+ (member value
+ '(#.sb!vm:no-tls-value-marker-widetag
+ #.sb!vm:unbound-marker-widetag))
+ (member obj seen :test #'eq))
+ collect obj into seen
+ finally (return seen))))))
+
+(defun symbol-value-in-thread (symbol thread &optional (errorp t))
+ "Return the local value of SYMBOL in THREAD, and a secondary value of T
+on success.
+
+If the value cannot be retrieved (because the thread has exited or because it
+has no local binding for NAME) and ERRORP is true signals an error of type
+SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
+NIL, and a secondary value of NIL.
+
+Can also be used with SETF to change the thread-local value of SYMBOL.
+
+SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
+mechanism for inter-thread communication."
+ (declare (symbol symbol) (thread thread))
+ #!+sb-thread
+ (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
+ (if (eq :ok status)
+ (values res t)
+ (if errorp
+ (error 'symbol-value-in-thread-error
+ :name symbol
+ :thread thread
+ :info (list :read status))
+ (values nil nil))))
+ #!-sb-thread
+ (if (boundp symbol)
+ (values (symbol-value symbol) t)
+ (if errorp
+ (error 'symbol-value-in-thread-error
+ :name symbol
+ :thread thread
+ :info (list :read :unbound-in-thread))
+ (values nil nil))))
+
+(defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
+ (declare (symbol symbol) (thread thread))
+ #!+sb-thread
+ (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
+ (if (eq :ok status)
+ (values res t)
+ (if errorp
+ (error 'symbol-value-in-thread-error
+ :name symbol
+ :thread thread
+ :info (list :write status))
+ (values nil nil))))
+ #!-sb-thread
+ (if (boundp symbol)
+ (values (setf (symbol-value symbol) value) t)
+ (if errorp
+ (error 'symbol-value-in-thread-error
+ :name symbol
+ :thread thread
+ :info (list :write :unbound-in-thread))
+ (values nil nil))))
+
+(defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
+ (sb!vm::locked-symbol-global-value-add symbol-name delta))
+\f
+
+;;;; Stepping
+
+(defun thread-stepping ()
+ (make-lisp-obj
+ (sap-ref-word (current-thread-sap)
+ (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
+
+(defun (setf thread-stepping) (value)
+ (setf (sap-ref-word (current-thread-sap)
+ (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
+ (get-lisp-obj-address value)))