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")
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.
19 ;;; set the doc here because in early-thread FDOCUMENTATION is not
22 (setf (fdocumentation '*current-thread* 'variable)
23 "Bound in each thread to the thread itself.")
25 (defstruct (thread (:constructor %make-thread))
27 "Thread type. Do not rely on threads being structs as it may change
33 (interruptions-lock (make-mutex :name "thread interruptions lock"))
35 (result-lock (make-mutex :name "thread result lock")))
38 (setf (fdocumentation 'thread-name 'function)
39 "The name of the thread. Setfable.")
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
51 (defun thread-alive-p (thread)
53 "Check if THREAD is running."
54 (thread-%alive-p thread))
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"))
62 (defmacro with-all-threads-lock (&body body)
63 `(with-system-mutex (*all-threads-lock*)
66 (defun list-all-threads ()
68 "Return a list of the live threads."
69 (with-all-threads-lock
70 (copy-list *all-threads*)))
72 (declaim (inline current-thread-sap))
73 (defun current-thread-sap ()
74 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
76 (declaim (inline current-thread-sap-id))
77 (defun current-thread-sap-id ()
79 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
81 (defun init-initial-thread ()
82 (/show0 "Entering INIT-INITIAL-THREAD")
83 (let ((initial-thread (%make-thread :name "initial thread"
85 :os-thread (current-thread-sap-id))))
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))))
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
100 (define-alien-routine ("create_thread" %create-thread)
101 unsigned-long (lisp-fun-address unsigned-long))
103 (define-alien-routine "signal_interrupt_thread"
104 integer (os-thread unsigned-long))
106 (define-alien-routine "block_deferrable_signals"
111 (declaim (inline %lutex-init %lutex-wait %lutex-wake
112 %lutex-lock %lutex-unlock))
114 (define-alien-routine ("lutex_init" %lutex-init)
115 int (lutex unsigned-long))
117 (define-alien-routine ("lutex_wait" %lutex-wait)
118 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
120 (define-alien-routine ("lutex_wake" %lutex-wake)
121 int (lutex unsigned-long) (n int))
123 (define-alien-routine ("lutex_lock" %lutex-lock)
124 int (lutex unsigned-long))
126 (define-alien-routine ("lutex_trylock" %lutex-trylock)
127 int (lutex unsigned-long))
129 (define-alien-routine ("lutex_unlock" %lutex-unlock)
130 int (lutex unsigned-long))
132 (define-alien-routine ("lutex_destroy" %lutex-destroy)
133 int (lutex unsigned-long))
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)))
146 (/show0 "Entering MAKE-LUTEX")
147 ;; Suppress GC until the lutex has been properly registered with
150 (let ((lutex (sb!vm::%make-lutex)))
153 (with-lutex-address (lutex lutex)
159 (declaim (inline futex-wait %futex-wait futex-wake))
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))
165 (defun futex-wait (word old to-sec to-usec)
167 (%futex-wait word old to-sec to-usec)))
169 (define-alien-routine "futex_wake"
170 int (word unsigned-long) (n unsigned-long))))
172 ;;; used by debug-int.lisp to access interrupt contexts
173 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
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)))
181 (defun sb!vm::current-thread-offset-sap (n)
182 (declare (type (unsigned-byte 27) n))
183 (sb!vm::current-thread-offset-sap n))
185 (declaim (inline get-spinlock release-spinlock))
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)))
194 (error "Recursive lock attempt on ~S." spinlock))
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.
203 (loop repeat 128 do (cas)) ; 128 is arbitrary here
204 (sb!unix::%check-interrupts))
208 (defun release-spinlock (spinlock)
209 (declare (optimize (speed 3) (safety 0)))
210 (setf (spinlock-value spinlock) nil)
216 (setf (fdocumentation 'make-mutex 'function)
218 (fdocumentation 'mutex-name 'function)
219 "The name of the mutex. Setfable.")
221 #!+(and sb-thread (not sb-lutex))
223 (define-structure-slot-addressor mutex-state-address
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))
232 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
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.
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.
241 GET-MUTEX is not interrupt safe. The correct way to call it is:
245 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
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.
252 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
254 (declare (type mutex mutex) (optimize (speed 3))
255 #!-sb-thread (ignore waitp))
257 (setq new-owner *current-thread*))
258 (when (eql new-owner (mutex-%owner mutex))
259 (error "Recursive lock attempt ~S." mutex))
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.
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.
272 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
274 (with-interrupts (%lutex-lock lutex))
275 (%lutex-trylock lutex))))
276 (setf (mutex-%owner mutex) new-owner)
279 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
282 (unless (or (eql +lock-free+ old) (not waitp))
285 (when (or (eql +lock-contested+ old)
286 (not (eql +lock-free+
287 (sb!ext:compare-and-swap (mutex-state mutex)
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+)
298 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
302 (unless (eql +lock-free+ old)
304 (cond ((eql +lock-free+ old)
305 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
308 (bug "Old owner in free mutex: ~S" prev))
311 (bug "Failed to acquire lock with WAITP."))))))
313 (defun release-mutex (mutex)
315 "Release MUTEX by setting it to NIL. Wake up threads waiting for
318 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
321 Signals a WARNING is current thread is not the current owner of the
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)))
333 (with-lutex-address (lutex (mutex-lutex mutex))
334 (%lutex-unlock 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))))
345 ;;;; waitqueues/condition variables
347 (defstruct (waitqueue (:constructor %make-waitqueue))
350 (name nil :type (or null simple-string))
351 #!+(and sb-lutex sb-thread)
356 (defun make-waitqueue (&key name)
358 "Create a waitqueue."
359 (%make-waitqueue :name name))
362 (setf (fdocumentation 'waitqueue-name 'function)
363 "The name of the waitqueue. Setfable.")
365 #!+(and sb-thread (not sb-lutex))
366 (define-structure-slot-addressor waitqueue-data-address
370 (defun condition-wait (queue mutex)
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))
377 #!-sb-thread (error "Not supported in unithread builds.")
379 (let ((owner (mutex-%owner mutex)))
380 (/show0 "CONDITION-WAITing")
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))
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,
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"
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))))
415 (defun condition-notify (queue &optional (n 1))
417 "Notify N threads waiting on QUEUE."
418 #!-sb-thread (declare (ignore queue n))
419 #!-sb-thread (error "Not supported in unithread builds.")
421 (declare (type (and fixnum (integer 1)) n))
422 (/show0 "Entering CONDITION-NOTIFY")
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
434 (let ((me *current-thread*))
436 (setf (waitqueue-data queue) me)
437 (with-pinned-objects (queue)
438 (futex-wake (waitqueue-data-address queue) n))))))
440 (defun condition-broadcast (queue)
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.
447 most-positive-fixnum)))
451 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
453 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
454 should be considered an implementation detail, and may change in the
456 (name nil :type (or null simple-string))
457 (%count 0 :type (integer 0))
459 (queue (make-waitqueue)))
461 (setf (fdocumentation 'semaphore-name 'function)
462 "The name of the semaphore INSTANCE. Setfable.")
464 (declaim (inline semaphore-count))
465 (defun semaphore-count (instance)
466 "Returns the current count of the semaphore INSTANCE."
467 (semaphore-%count instance))
469 (defun make-semaphore (&key name (count 0))
471 "Create a semaphore with the supplied COUNT and NAME."
472 (%make-semaphore name count))
474 (defun wait-on-semaphore (semaphore)
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
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)))))
485 (defun signal-semaphore (semaphore &optional (n 1))
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))))
494 ;;;; job control, independent listeners
497 (lock (make-mutex :name "session lock"))
499 (interactive-threads nil)
500 (interactive-threads-queue (make-waitqueue)))
502 (defvar *session* nil)
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.
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.)
514 ;;; FIXME: It would be good to have ordered locks to ensure invariants like
516 (defmacro with-session-lock ((session) &body body)
517 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
520 (defun new-session ()
521 (make-session :threads (list *current-thread*)
522 :interactive-threads (list *current-thread*)))
524 (defun init-job-control ()
525 (/show0 "Entering INIT-JOB-CONTROL")
526 (setf *session* (new-session))
527 (/show0 "Exiting INIT-JOB-CONTROL"))
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)))))
536 (defun call-with-new-session (fn)
537 (%delete-thread-from-session *current-thread* *session*)
538 (let ((*session* (new-session)))
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)))))
547 ;;; Remove thread from its session, if it has one.
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)
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*))
560 (%delete-thread-from-session thread *session*)))
563 (/show0 "FREEING MUTEX LUTEX")
564 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
565 (%lutex-destroy lutex))))
567 (defun terminate-session ()
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
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 ()))))))
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
590 (declare (ignore stream))
594 (with-session-lock (*session*)
595 (not (member *current-thread*
596 (session-interactive-threads *session*))))
599 (defun get-foreground ()
602 (let ((was-foreground t))
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*)))
616 (session-interactive-threads-queue *session*)
617 (session-lock *session*)))))))
619 (defun release-foreground (&optional next)
621 "Background this thread. If NEXT is supplied, arrange for it to
622 have the foreground next."
623 #!-sb-thread (declare (ignore next))
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*))))
631 (setf (session-interactive-threads *session*)
633 (delete next (session-interactive-threads *session*)))))
634 (condition-broadcast (session-interactive-threads-queue *session*))))
636 (defun foreground-thread ()
637 (car (session-interactive-threads *session*)))
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
650 (make-fd-stream out :output t :buffering :line
653 (make-fd-stream err :output t :buffering :line
656 (make-fd-stream err :input t :output t
659 (sb!impl::*descriptor-handlers* nil))
662 (sb!impl::toplevel-repl nil)
663 (sb!int:flush-standard-output-streams))))))
664 (make-thread #'thread-repl))))
668 (defun make-thread (function &key name)
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.")
676 (let* ((thread (%make-thread :name name))
677 (setup-sem (make-semaphore :name "Thread setup semaphore"))
678 (real-function (coerce function 'function))
681 ;; In time we'll move some of the binding presently done in C
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.
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)
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-sap-id))
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
723 "~~@<Terminate this thread (~A)~~@:>"
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)
734 (funcall real-function)))))
735 (handle-thread-exit thread)))))))
737 ;; Keep INITIAL-FUNCTION pinned until the child thread is
738 ;; initialized properly.
739 (with-pinned-objects (initial-function)
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)
748 (define-condition join-thread-error (error)
749 ((thread :reader join-thread-error-thread :initarg :thread))
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)))))
758 (setf (fdocumentation 'join-thread-error-thread 'function)
759 "The thread that we failed to join.")
761 (defun join-thread (thread &key (default nil defaultp))
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))))
772 (error 'join-thread-error :thread thread)))))
774 (defun destroy-thread (thread)
776 "Deprecated. Same as TERMINATE-THREAD."
777 (terminate-thread thread))
779 (define-condition interrupt-thread-error (error)
780 ((thread :reader interrupt-thread-error-thread :initarg :thread))
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)))))
788 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
789 "The thread that was not interrupted.")
791 (defmacro with-interruptions-lock ((thread) &body body)
792 `(with-system-mutex ((thread-interruptions-lock ,thread))
795 ;; Called from the signal handler in C.
796 (defun run-interruption ()
799 (let ((interruption (with-interruptions-lock (*current-thread*)
800 (pop (thread-interruptions *current-thread*)))))
803 (funcall interruption))
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
813 (defun interrupt-thread (thread function)
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))
822 (with-interrupt-bindings
823 (with-interrupts (funcall function)))
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))
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)))))))
837 (defun terminate-thread (thread)
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))
843 ;;; internal use only. If you think you need to use this, either you
844 ;;; are an SBCL developer, are doing something that you should discuss
845 ;;; with an SBCL developer first, or are doing something that you
846 ;;; should probably discuss with a professional psychiatrist first
848 (defun thread-sap-for-id (id)
849 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
851 (when (sap= thread-sap (int-sap 0)) (return nil))
852 (let ((os-thread (sap-ref-word thread-sap
853 (* sb!vm:n-word-bytes
854 sb!vm::thread-os-thread-slot))))
855 (when (= os-thread id) (return thread-sap))
857 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
858 sb!vm::thread-next-slot)))))))
860 (define-alien-routine "thread_yield" int)
863 (setf (fdocumentation 'thread-yield 'function)
864 "Yield the processor to other threads.")
867 (defun symbol-value-in-thread (symbol thread-sap)
868 (let* ((index (sb!vm::symbol-tls-index symbol))
869 (tl-val (sap-ref-word thread-sap
870 (* sb!vm:n-word-bytes index))))
871 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
872 (sb!vm::symbol-global-value symbol)
873 (make-lisp-obj tl-val))))
875 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
876 (sb!vm::locked-symbol-global-value-add symbol-name delta))
880 (defun thread-stepping ()
882 (sap-ref-word (current-thread-sap)
883 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
885 (defun (setf thread-stepping) (value)
886 (setf (sap-ref-word (current-thread-sap)
887 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
888 (get-lisp-obj-address value)))