-already the foreground thread, or transfers control to the first applicable
-restart if *BACKGROUND-THREADS-WAIT-FOR-DEBUGGER* says to do that instead"
- (let* ((wait-p *background-threads-wait-for-debugger*)
- (*background-threads-wait-for-debugger* nil)
- (lock *session-lock*))
- (when (not (eql (mutex-value lock) (CURRENT-THREAD-ID)))
- (when (functionp wait-p)
- (setf wait-p
- (funcall wait-p stream (CURRENT-THREAD-ID))))
- (cond (wait-p (get-foreground))
- (t (invoke-restart (car (compute-restarts))))))))
-
-;;; install this with
-;;; (setf SB-INT:*REPL-PROMPT-FUN* #'sb-thread::thread-repl-prompt-fun)
-;;; One day it will be default
-(defun thread-repl-prompt-fun (out-stream)
- (let ((lock *session-lock*))
- (get-foreground)
- (let ((stopped-threads (waitqueue-data lock)))
- (when stopped-threads
- (format out-stream "~{~&Thread ~A suspended~}~%" stopped-threads))
- (sb!impl::repl-prompt-fun out-stream))))
-
-(defun resume-stopped-thread (id)
- (let ((lock *session-lock*))
- (with-spinlock (lock)
- (setf (waitqueue-data lock)
- (cons id (delete id (waitqueue-data lock)))))
- (release-foreground)))
-
-(defstruct rwlock
- (name nil :type (or null simple-base-string))
- (value 0 :type fixnum)
- (max-readers nil :type (or fixnum null))
- (max-writers 1 :type fixnum))
-#+nil
-(macrolet
- ((make-rwlocking-function (lock-fn unlock-fn increment limit test)
- (let ((do-update '(when (eql old-value
- (sb!vm::%instance-set-conditional
- lock 2 old-value new-value))
- (return (values t old-value))))
- (vars `((timeout (and timeout (+ (get-internal-real-time) timeout)))
- old-value
- new-value
- (limit ,limit))))
- (labels ((do-setfs (v) `(setf old-value (rwlock-value lock)
- new-value (,v old-value ,increment))))
- `(progn
- (defun ,lock-fn (lock timeout)
- (declare (type rwlock lock))
- (let ,vars
- (loop
- ,(do-setfs '+)
- (when ,test
- ,do-update)
- (when (sleep-a-bit timeout) (return nil)) ;expired
- )))
- ;; unlock doesn't need timeout or test-in-range
- (defun ,unlock-fn (lock)
- (declare (type rwlock lock))
- (declare (ignorable limit))
- (let ,(cdr vars)
- (loop
- ,(do-setfs '-)
- ,do-update))))))))
-
- (make-rwlocking-function %lock-for-reading %unlock-for-reading 1
- (rwlock-max-readers lock)
- (and (>= old-value 0)
- (or (null limit) (<= new-value limit))))
- (make-rwlocking-function %lock-for-writing %unlock-for-writing -1
- (- (rwlock-max-writers lock))
- (and (<= old-value 0)
- (>= new-value limit))))
-#+nil
-(defun get-rwlock (lock direction &optional timeout)
- (ecase direction
- (:read (%lock-for-reading lock timeout))
- (:write (%lock-for-writing lock timeout))))
-#+nil
-(defun free-rwlock (lock direction)
- (ecase direction
- (:read (%unlock-for-reading lock))
- (:write (%unlock-for-writing lock))))
-
-;;;; beyond this point all is commented.
-
-;;; Lock-Wait-With-Timeout -- Internal
-;;;
-;;; Wait with a timeout for the lock to be free and acquire it for the
-;;; *current-process*.
-;;;
-#+nil
-(defun lock-wait-with-timeout (lock whostate timeout)
- (declare (type lock lock))
- (process-wait-with-timeout
- whostate timeout
- #'(lambda ()
- (declare (optimize (speed 3)))
- #-i486
- (unless (lock-process lock)
- (setf (lock-process lock) *current-process*))
- #+i486
- (null (kernel:%instance-set-conditional
- lock 2 nil *current-process*)))))
-
-;;; With-Lock-Held -- Public
-;;;
-#+nil
-(defmacro with-lock-held ((lock &optional (whostate "Lock Wait")
- &key (wait t) timeout)
- &body body)
- "Execute the body with the lock held. If the lock is held by another
- process then the current process waits until the lock is released or
- an optional timeout is reached. The optional wait timeout is a time in
- seconds acceptable to process-wait-with-timeout. The results of the
- body are return upon success and NIL is return if the timeout is
- reached. When the wait key is NIL and the lock is held by another
- process then NIL is return immediately without processing the body."
- (let ((have-lock (gensym)))
- `(let ((,have-lock (eq (lock-process ,lock) *current-process*)))
- (unwind-protect
- ,(cond ((and timeout wait)
- `(progn
- (when (and (error-check-lock-p ,lock) ,have-lock)
- (error "Dead lock"))
- (when (or ,have-lock
- #+i486 (null (kernel:%instance-set-conditional
- ,lock 2 nil *current-process*))
- #-i486 (seize-lock ,lock)
- (if ,timeout
- (lock-wait-with-timeout
- ,lock ,whostate ,timeout)
- (lock-wait ,lock ,whostate)))
- ,@body)))
- (wait
- `(progn
- (when (and (error-check-lock-p ,lock) ,have-lock)
- (error "Dead lock"))
- (unless (or ,have-lock
- #+i486 (null (kernel:%instance-set-conditional
- ,lock 2 nil *current-process*))
- #-i486 (seize-lock ,lock))
- (lock-wait ,lock ,whostate))
- ,@body))
- (t
- `(when (or (and (recursive-lock-p ,lock) ,have-lock)
- #+i486 (null (kernel:%instance-set-conditional
- ,lock 2 nil *current-process*))
- #-i486 (seize-lock ,lock))
- ,@body)))
- (unless ,have-lock
- #+i486 (kernel:%instance-set-conditional
- ,lock 2 *current-process* nil)
- #-i486 (when (eq (lock-process ,lock) *current-process*)
- (setf (lock-process ,lock) nil)))))))
+interactive."
+ (declare (ignore stream))
+ #!-sb-thread nil
+ #!+sb-thread
+ (prog1
+ (with-session-lock (*session*)
+ (not (member *current-thread*
+ (session-interactive-threads *session*))))
+ (get-foreground)))
+
+(defun get-foreground ()
+ #!-sb-thread t
+ #!+sb-thread
+ (let ((was-foreground t))
+ (loop
+ (/show0 "Looping in GET-FOREGROUND")
+ (with-session-lock (*session*)
+ (let ((int-t (session-interactive-threads *session*)))
+ (when (eq (car int-t) *current-thread*)
+ (unless was-foreground
+ (format *query-io* "Resuming thread ~A~%" *current-thread*))
+ (return-from get-foreground t))
+ (setf was-foreground nil)
+ (unless (member *current-thread* int-t)
+ (setf (cdr (last int-t))
+ (list *current-thread*)))
+ (condition-wait
+ (session-interactive-threads-queue *session*)
+ (session-lock *session*)))))))
+
+(defun release-foreground (&optional next)
+ #!+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)
+ #!+sb-doc
+ "Create a new thread of NAME that runs FUNCTION. 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))
+ #!-sb-thread (error "Not supported in unithread builds.")
+ #!+sb-thread
+ (let* ((thread (%make-thread :name name))
+ (setup-sem (make-semaphore :name "Thread setup semaphore"))
+ (real-function (coerce function 'function))
+ (initial-function
+ (lambda ()
+ ;; 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::*step-out* nil)
+ ;; internal printer variables
+ (sb!impl::*previous-case* nil)
+ (sb!impl::*previous-readtable-case* nil)
+ (empty (vector))
+ (sb!impl::*merge-sort-temp-vector* empty)
+ (sb!impl::*zap-array-data-temp* empty)
+ (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
+ (funcall real-function))))
+ ;; 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))
+ #!+sb-doc
+ "Suspend current thread until THREAD exits. Returns the result
+values of the thread function. If the thread does not exit normally,
+return DEFAULT if given or else signal JOIN-THREAD-ERROR."
+ (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
+ (cond ((car (thread-result thread))
+ (return-from join-thread
+ (values-list (cdr (thread-result thread)))))
+ (defaultp
+ (return-from join-thread default))))
+ (error 'join-thread-error :thread thread))
+
+(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 the live THREAD and make it run FUNCTION. A moderate
+degree of care is expected for use of INTERRUPT-THREAD, due to its
+nature: if you interrupt a thread that was holding important locks
+then do something that turns out to need those locks, you probably
+won't like the effect. FUNCTION runs with interrupts disabled, but
+WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
+enable interrupts (GET-MUTEX when contended, for instance) so the
+first thing to do is usually a WITH-INTERRUPTS or a
+WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
+run in same the order they were sent."
+ #!+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 causing it to run
+SB-EXT:QUIT - the usual cleanup forms will be evaluated"
+ (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* ((epoch sb!kernel::*gc-epoch*)
+ (offset (* sb!vm:n-word-bytes
+ (sb!vm::symbol-tls-index symbol)))
+ (tl-val (sap-ref-word (%thread-sap thread) offset)))
+ (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
+ (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
+ ;; The value we constructed may be invalid if a GC has
+ ;; occurred. That is harmless, though, since OBJ is
+ ;; either in a register or on stack, and we are
+ ;; conservative on both on GENCGC -- so a bogus object
+ ;; is safe here as long as we don't return it. If we
+ ;; ever port threads to a non-conservative GC we must
+ ;; pin the TL-VAL address before constructing OBJ, or
+ ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
+ ;;
+ ;; The reason we don't just rely on TL-VAL pinning the
+ ;; object is that the call to MAKE-LISP-OBJ may cause
+ ;; bignum allocation, at which point TL-VAL might not
+ ;; be alive anymore -- hence the epoch check.
+ (when (eq epoch sb!kernel::*gc-epoch*)
+ (if ok
+ (return (values obj :ok))
+ (return (values obj :invalid-tls-value))))))))
+ (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!vm:n-word-bytes
+ (sb!vm::symbol-tls-index symbol))))
+ (cond ((zerop offset)
+ (values nil :no-tls-value))
+ (t
+ (setf (sap-ref-word (%thread-sap thread) offset)
+ (get-lisp-obj-address value))
+ (values value :ok))))
+ (values nil :thread-dead))))))
+
+(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