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 (print-unreadable-object (thread stream :type t :identity t)
43 (let* ((cookie (list thread))
44 (info (if (thread-alive-p thread)
46 (multiple-value-list (join-thread thread :default cookie))))
47 (state (if (eq :running info)
49 (if (eq cookie (car info))
52 (values (when (eq :finished state) info)))
53 (format stream "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
59 (defun thread-alive-p (thread)
61 "Check if THREAD is running."
62 (thread-%alive-p thread))
64 ;; A thread is eligible for gc iff it has finished and there are no
65 ;; more references to it. This list is supposed to keep a reference to
66 ;; all running threads.
67 (defvar *all-threads* ())
68 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
70 (defmacro with-all-threads-lock (&body body)
71 `(with-system-mutex (*all-threads-lock*)
74 (defun list-all-threads ()
76 "Return a list of the live threads."
77 (with-all-threads-lock
78 (copy-list *all-threads*)))
80 (declaim (inline current-thread-sap))
81 (defun current-thread-sap ()
82 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
84 (declaim (inline current-thread-os-thread))
85 (defun current-thread-os-thread ()
87 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
89 (defun init-initial-thread ()
90 (/show0 "Entering INIT-INITIAL-THREAD")
91 (let ((initial-thread (%make-thread :name "initial thread"
93 :os-thread (current-thread-os-thread))))
94 (setq *current-thread* initial-thread)
95 ;; Either *all-threads* is empty or it contains exactly one thread
96 ;; in case we are in reinit since saving core with multiple
97 ;; threads doesn't work.
98 (setq *all-threads* (list initial-thread))))
104 ;; FIXME it would be good to define what a thread id is or isn't
105 ;; (our current assumption is that it's a fixnum). It so happens
106 ;; that on Linux it's a pid, but it might not be on posix thread
108 (define-alien-routine ("create_thread" %create-thread)
109 unsigned-long (lisp-fun-address unsigned-long))
111 (define-alien-routine "signal_interrupt_thread"
112 integer (os-thread unsigned-long))
114 (define-alien-routine "block_deferrable_signals"
119 (declaim (inline %lutex-init %lutex-wait %lutex-wake
120 %lutex-lock %lutex-unlock))
122 (define-alien-routine ("lutex_init" %lutex-init)
123 int (lutex unsigned-long))
125 (define-alien-routine ("lutex_wait" %lutex-wait)
126 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
128 (define-alien-routine ("lutex_wake" %lutex-wake)
129 int (lutex unsigned-long) (n int))
131 (define-alien-routine ("lutex_lock" %lutex-lock)
132 int (lutex unsigned-long))
134 (define-alien-routine ("lutex_trylock" %lutex-trylock)
135 int (lutex unsigned-long))
137 (define-alien-routine ("lutex_unlock" %lutex-unlock)
138 int (lutex unsigned-long))
140 (define-alien-routine ("lutex_destroy" %lutex-destroy)
141 int (lutex unsigned-long))
143 ;; FIXME: Defining a whole bunch of alien-type machinery just for
144 ;; passing primitive lutex objects directly to foreign functions
145 ;; doesn't seem like fun right now. So instead we just manually
146 ;; pin the lutex, get its address, and let the callee untag it.
147 (defmacro with-lutex-address ((name lutex) &body body)
148 `(let ((,name ,lutex))
149 (with-pinned-objects (,name)
150 (let ((,name (get-lisp-obj-address ,name)))
154 (/show0 "Entering MAKE-LUTEX")
155 ;; Suppress GC until the lutex has been properly registered with
158 (let ((lutex (sb!vm::%make-lutex)))
161 (with-lutex-address (lutex lutex)
167 (declaim (inline futex-wait %futex-wait futex-wake))
169 (define-alien-routine ("futex_wait" %futex-wait)
170 int (word unsigned-long) (old-value unsigned-long)
171 (to-sec long) (to-usec unsigned-long))
173 (defun futex-wait (word old to-sec to-usec)
175 (%futex-wait word old to-sec to-usec)))
177 (define-alien-routine "futex_wake"
178 int (word unsigned-long) (n unsigned-long))))
180 ;;; used by debug-int.lisp to access interrupt contexts
181 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
183 (defun sb!vm::current-thread-offset-sap (n)
184 (declare (type (unsigned-byte 27) n))
185 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
186 (* n sb!vm:n-word-bytes)))
189 (defun sb!vm::current-thread-offset-sap (n)
190 (declare (type (unsigned-byte 27) n))
191 (sb!vm::current-thread-offset-sap n))
193 (declaim (inline get-spinlock release-spinlock))
195 ;; Should always be called with interrupts disabled.
196 (defun get-spinlock (spinlock)
197 (declare (optimize (speed 3) (safety 0)))
198 (let* ((new *current-thread*)
199 (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
202 (error "Recursive lock attempt on ~S." spinlock))
205 (unless (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
206 (return-from get-spinlock t))))
207 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
208 ;; If interrupts are enabled, but we are allowed to enabled them,
209 ;; check for pending interrupts every once in a while.
211 (loop repeat 128 do (cas)) ; 128 is arbitrary here
212 (sb!unix::%check-interrupts))
216 (defun release-spinlock (spinlock)
217 (declare (optimize (speed 3) (safety 0)))
218 (setf (spinlock-value spinlock) nil)
224 (setf (fdocumentation 'make-mutex 'function)
226 (fdocumentation 'mutex-name 'function)
227 "The name of the mutex. Setfable.")
229 #!+(and sb-thread (not sb-lutex))
231 (define-structure-slot-addressor mutex-state-address
234 ;; Important: current code assumes these are fixnums or other
235 ;; lisp objects that don't need pinning.
236 (defconstant +lock-free+ 0)
237 (defconstant +lock-taken+ 1)
238 (defconstant +lock-contested+ 2))
240 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
242 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
243 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
244 non-NIL and the mutex is in use, sleep until it is available.
246 Note: using GET-MUTEX to assign a MUTEX to another thread then the
247 current one is not recommended, and liable to be deprecated.
249 GET-MUTEX is not interrupt safe. The correct way to call it is:
253 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
256 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
257 call while the mutex is in an inconsistent state while
258 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
260 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
262 (declare (type mutex mutex) (optimize (speed 3))
263 #!-sb-thread (ignore waitp))
265 (setq new-owner *current-thread*))
266 (when (eql new-owner (mutex-%owner mutex))
267 (error "Recursive lock attempt ~S." mutex))
270 ;; FIXME: Lutexes do not currently support deadlines, as at least
271 ;; on Darwin pthread_foo_timedbar functions are not supported:
272 ;; this means that we probably need to use the Carbon multiprocessing
273 ;; functions on Darwin.
275 ;; FIXME: This is definitely not interrupt safe: what happens if
276 ;; we get hit (1) during the lutex calls (ok, they may be safe,
277 ;; but has that been checked?) (2) after the lutex call, but
278 ;; before setting the mutex owner.
280 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
282 (with-interrupts (%lutex-lock lutex))
283 (%lutex-trylock lutex))))
284 (setf (mutex-%owner mutex) new-owner)
287 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
290 (unless (or (eql +lock-free+ old) (not waitp))
293 (when (or (eql +lock-contested+ old)
294 (not (eql +lock-free+
295 (sb!ext:compare-and-swap (mutex-state mutex)
298 ;; Wait on the contested lock.
299 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
300 (when (= 1 (with-pinned-objects (mutex)
301 (futex-wait (mutex-state-address mutex)
302 (get-lisp-obj-address +lock-contested+)
306 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
310 (unless (eql +lock-free+ old)
312 (cond ((eql +lock-free+ old)
313 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
316 (bug "Old owner in free mutex: ~S" prev))
319 (bug "Failed to acquire lock with WAITP."))))))
321 (defun release-mutex (mutex)
323 "Release MUTEX by setting it to NIL. Wake up threads waiting for
326 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
329 Signals a WARNING is current thread is not the current owner of the
331 (declare (type mutex mutex))
332 ;; Order matters: set owner to NIL before releasing state.
333 (let* ((self *current-thread*)
334 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
335 (unless (eql self old-owner)
336 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
337 (setf (mutex-%owner mutex) nil)))
341 (with-lutex-address (lutex (mutex-lutex mutex))
342 (%lutex-unlock lutex))
344 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
345 +lock-taken+ +lock-free+)))
346 (when (eql old +lock-contested+)
347 (sb!ext:compare-and-swap (mutex-state mutex)
348 +lock-contested+ +lock-free+)
349 (with-pinned-objects (mutex)
350 (futex-wake (mutex-state-address mutex) 1))))
353 ;;;; waitqueues/condition variables
355 (defstruct (waitqueue (:constructor %make-waitqueue))
358 (name nil :type (or null simple-string))
359 #!+(and sb-lutex sb-thread)
364 (defun make-waitqueue (&key name)
366 "Create a waitqueue."
367 (%make-waitqueue :name name))
370 (setf (fdocumentation 'waitqueue-name 'function)
371 "The name of the waitqueue. Setfable.")
373 #!+(and sb-thread (not sb-lutex))
374 (define-structure-slot-addressor waitqueue-data-address
378 (defun condition-wait (queue mutex)
380 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
381 thread may subsequently notify us using CONDITION-NOTIFY, at which
382 time we reacquire MUTEX and return to the caller."
383 #!-sb-thread (declare (ignore queue))
385 #!-sb-thread (error "Not supported in unithread builds.")
387 (let ((owner (mutex-%owner mutex)))
388 (/show0 "CONDITION-WAITing")
391 ;; FIXME: This doesn't look interrupt safe!
392 (setf (mutex-%owner mutex) nil)
393 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
394 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
395 (%lutex-wait queue-lutex-address mutex-lutex-address)))
396 (setf (mutex-%owner mutex) owner))
399 (let ((me *current-thread*))
400 ;; FIXME: should we do something to ensure that the result
401 ;; of this setf is visible to all CPUs?
402 (setf (waitqueue-data queue) me)
403 (release-mutex mutex)
404 ;; Now we go to sleep using futex-wait. If anyone else
405 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
406 ;; this comment, it will change queue->data, and so
407 ;; futex-wait returns immediately instead of sleeping.
408 ;; Ergo, no lost wakeup. We may get spurious wakeups,
410 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
411 (when (= 1 (with-pinned-objects (queue me)
412 (futex-wait (waitqueue-data-address queue)
413 (get-lisp-obj-address me)
414 (or to-sec -1) ;; our way if saying "no timeout"
417 ;; If we are interrupted while waiting, we should do these things
418 ;; before returning. Ideally, in the case of an unhandled signal,
419 ;; we should do them before entering the debugger, but this is
420 ;; better than nothing.
421 (get-mutex mutex owner))))
423 (defun condition-notify (queue &optional (n 1))
425 "Notify N threads waiting on QUEUE."
426 #!-sb-thread (declare (ignore queue n))
427 #!-sb-thread (error "Not supported in unithread builds.")
429 (declare (type (and fixnum (integer 1)) n))
430 (/show0 "Entering CONDITION-NOTIFY")
434 (with-lutex-address (lutex (waitqueue-lutex queue))
435 (%lutex-wake lutex n))
436 ;; no problem if >1 thread notifies during the comment in
437 ;; condition-wait: as long as the value in queue-data isn't the
438 ;; waiting thread's id, it matters not what it is
439 ;; XXX we should do something to ensure that the result of this setf
440 ;; is visible to all CPUs
442 (let ((me *current-thread*))
444 (setf (waitqueue-data queue) me)
445 (with-pinned-objects (queue)
446 (futex-wake (waitqueue-data-address queue) n))))))
448 (defun condition-broadcast (queue)
450 "Notify all threads waiting on QUEUE."
451 (condition-notify queue
452 ;; On a 64-bit platform truncating M-P-F to an int results
453 ;; in -1, which wakes up only one thread.
455 most-positive-fixnum)))
459 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
461 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
462 should be considered an implementation detail, and may change in the
464 (name nil :type (or null simple-string))
465 (%count 0 :type (integer 0))
467 (queue (make-waitqueue)))
469 (setf (fdocumentation 'semaphore-name 'function)
470 "The name of the semaphore INSTANCE. Setfable.")
472 (declaim (inline semaphore-count))
473 (defun semaphore-count (instance)
474 "Returns the current count of the semaphore INSTANCE."
475 (semaphore-%count instance))
477 (defun make-semaphore (&key name (count 0))
479 "Create a semaphore with the supplied COUNT and NAME."
480 (%make-semaphore name count))
482 (defun wait-on-semaphore (semaphore)
484 "Decrement the count of SEMAPHORE if the count would not be
485 negative. Else blocks until the semaphore can be decremented."
486 ;; a more direct implementation based directly on futexes should be
488 (with-mutex ((semaphore-mutex semaphore))
489 (loop until (> (semaphore-%count semaphore) 0)
490 do (condition-wait (semaphore-queue semaphore) (semaphore-mutex semaphore))
491 finally (decf (semaphore-%count semaphore)))))
493 (defun signal-semaphore (semaphore &optional (n 1))
495 "Increment the count of SEMAPHORE by N. If there are threads waiting
496 on this semaphore, then N of them is woken up."
497 (declare (type (integer 1) n))
498 (with-mutex ((semaphore-mutex semaphore))
499 (when (= n (incf (semaphore-%count semaphore) n))
500 (condition-notify (semaphore-queue semaphore) n))))
502 ;;;; job control, independent listeners
505 (lock (make-mutex :name "session lock"))
507 (interactive-threads nil)
508 (interactive-threads-queue (make-waitqueue)))
510 (defvar *session* nil)
512 ;;; The debugger itself tries to acquire the session lock, don't let
513 ;;; funny situations (like getting a sigint while holding the session
514 ;;; lock) occur. At the same time we need to allow interrupts while
515 ;;; *waiting* for the session lock for things like GET-FOREGROUND
516 ;;; to be interruptible.
518 ;;; Take care: we sometimes need to obtain the session lock while holding
519 ;;; on to *ALL-THREADS-LOCK*, so we must _never_ obtain it _after_ getting
520 ;;; a session lock! (Deadlock risk.)
522 ;;; FIXME: It would be good to have ordered locks to ensure invariants like
524 (defmacro with-session-lock ((session) &body body)
525 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
528 (defun new-session ()
529 (make-session :threads (list *current-thread*)
530 :interactive-threads (list *current-thread*)))
532 (defun init-job-control ()
533 (/show0 "Entering INIT-JOB-CONTROL")
534 (setf *session* (new-session))
535 (/show0 "Exiting INIT-JOB-CONTROL"))
537 (defun %delete-thread-from-session (thread session)
538 (with-session-lock (session)
539 (setf (session-threads session)
540 (delete thread (session-threads session))
541 (session-interactive-threads session)
542 (delete thread (session-interactive-threads session)))))
544 (defun call-with-new-session (fn)
545 (%delete-thread-from-session *current-thread* *session*)
546 (let ((*session* (new-session)))
549 (defmacro with-new-session (args &body forms)
550 (declare (ignore args)) ;for extensibility
551 (sb!int:with-unique-names (fb-name)
552 `(labels ((,fb-name () ,@forms))
553 (call-with-new-session (function ,fb-name)))))
555 ;;; Remove thread from its session, if it has one.
557 (defun handle-thread-exit (thread)
558 (/show0 "HANDLING THREAD EXIT")
559 ;; We're going down, can't handle interrupts sanely anymore.
560 ;; GC remains enabled.
561 (block-deferrable-signals)
563 (with-all-threads-lock
564 (setf (thread-%alive-p thread) nil)
565 (setf (thread-os-thread thread) nil)
566 (setq *all-threads* (delete thread *all-threads*))
568 (%delete-thread-from-session thread *session*)))
571 (/show0 "FREEING MUTEX LUTEX")
572 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
573 (%lutex-destroy lutex))))
575 (defun terminate-session ()
577 "Kill all threads in session except for this one. Does nothing if current
578 thread is not the foreground thread."
579 ;; FIXME: threads created in other threads may escape termination
581 (with-session-lock (*session*)
582 (and (eq *current-thread*
583 (car (session-interactive-threads *session*)))
584 (session-threads *session*)))))
585 ;; do the kill after dropping the mutex; unwind forms in dying
586 ;; threads may want to do session things
587 (dolist (thread to-kill)
588 (unless (eq thread *current-thread*)
589 ;; terminate the thread but don't be surprised if it has
590 ;; exited in the meantime
591 (handler-case (terminate-thread thread)
592 (interrupt-thread-error ()))))))
594 ;;; called from top of invoke-debugger
595 (defun debugger-wait-until-foreground-thread (stream)
596 "Returns T if thread had been running in background, NIL if it was
598 (declare (ignore stream))
602 (with-session-lock (*session*)
603 (not (member *current-thread*
604 (session-interactive-threads *session*))))
607 (defun get-foreground ()
610 (let ((was-foreground t))
612 (/show0 "Looping in GET-FOREGROUND")
613 (with-session-lock (*session*)
614 (let ((int-t (session-interactive-threads *session*)))
615 (when (eq (car int-t) *current-thread*)
616 (unless was-foreground
617 (format *query-io* "Resuming thread ~A~%" *current-thread*))
618 (return-from get-foreground t))
619 (setf was-foreground nil)
620 (unless (member *current-thread* int-t)
621 (setf (cdr (last int-t))
622 (list *current-thread*)))
624 (session-interactive-threads-queue *session*)
625 (session-lock *session*)))))))
627 (defun release-foreground (&optional next)
629 "Background this thread. If NEXT is supplied, arrange for it to
630 have the foreground next."
631 #!-sb-thread (declare (ignore next))
634 (with-session-lock (*session*)
635 (when (rest (session-interactive-threads *session*))
636 (setf (session-interactive-threads *session*)
637 (delete *current-thread* (session-interactive-threads *session*))))
639 (setf (session-interactive-threads *session*)
641 (delete next (session-interactive-threads *session*)))))
642 (condition-broadcast (session-interactive-threads-queue *session*))))
644 (defun foreground-thread ()
645 (car (session-interactive-threads *session*)))
647 (defun make-listener-thread (tty-name)
648 (assert (probe-file tty-name))
649 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
650 (out (sb!unix:unix-dup in))
651 (err (sb!unix:unix-dup in)))
652 (labels ((thread-repl ()
653 (sb!unix::unix-setsid)
654 (let* ((sb!impl::*stdin*
655 (make-fd-stream in :input t :buffering :line
658 (make-fd-stream out :output t :buffering :line
661 (make-fd-stream err :output t :buffering :line
664 (make-fd-stream err :input t :output t
667 (sb!impl::*descriptor-handlers* nil))
670 (sb!impl::toplevel-repl nil)
671 (sb!int:flush-standard-output-streams))))))
672 (make-thread #'thread-repl))))
676 (defun make-thread (function &key name)
678 "Create a new thread of NAME that runs FUNCTION. When the function
679 returns the thread exits. The return values of FUNCTION are kept
680 around and can be retrieved by JOIN-THREAD."
681 #!-sb-thread (declare (ignore function name))
682 #!-sb-thread (error "Not supported in unithread builds.")
684 (let* ((thread (%make-thread :name name))
685 (setup-sem (make-semaphore :name "Thread setup semaphore"))
686 (real-function (coerce function 'function))
689 ;; In time we'll move some of the binding presently done in C
692 ;; KLUDGE: Here we have a magic list of variables that are
693 ;; not thread-safe for one reason or another. As people
694 ;; report problems with the thread safety of certain
695 ;; variables, (e.g. "*print-case* in multiple threads
696 ;; broken", sbcl-devel 2006-07-14), we add a few more
697 ;; bindings here. The Right Thing is probably some variant
698 ;; of Allegro's *cl-default-special-bindings*, as that is at
699 ;; least accessible to users to secure their own libraries.
701 (let* ((*current-thread* thread)
702 (*restart-clusters* nil)
703 (*handler-clusters* nil)
704 (*condition-restarts* nil)
705 (sb!impl::*deadline* nil)
706 (sb!impl::*step-out* nil)
707 ;; internal printer variables
708 (sb!impl::*previous-case* nil)
709 (sb!impl::*previous-readtable-case* nil)
711 (sb!impl::*merge-sort-temp-vector* empty)
712 (sb!impl::*zap-array-data-temp* empty)
713 (sb!impl::*internal-symbol-output-fun* nil)
714 (sb!impl::*descriptor-handlers* nil)) ; serve-event
715 (setf (thread-os-thread thread) (current-thread-os-thread))
716 (with-mutex ((thread-result-lock thread))
717 (with-all-threads-lock
718 (push thread *all-threads*))
719 (with-session-lock (*session*)
720 (push thread (session-threads *session*)))
721 (setf (thread-%alive-p thread) t)
722 (signal-semaphore setup-sem)
723 ;; can't use handling-end-of-the-world, because that flushes
724 ;; output streams, and we don't necessarily have any (or we
725 ;; could be sharing them)
726 (catch 'sb!impl::toplevel-catcher
727 (catch 'sb!impl::%end-of-the-world
731 "~~@<Terminate this thread (~A)~~@:>"
735 ;; now that most things have a chance to
736 ;; work properly without messing up other
737 ;; threads, it's time to enable signals
738 (sb!unix::reset-signal-mask)
739 (setf (thread-result thread)
742 (funcall real-function)))))
743 (handle-thread-exit thread)))))))
745 ;; Keep INITIAL-FUNCTION pinned until the child thread is
746 ;; initialized properly.
747 (with-pinned-objects (initial-function)
750 (get-lisp-obj-address initial-function))))
751 (when (zerop os-thread)
752 (error "Can't create a new thread"))
753 (wait-on-semaphore setup-sem)
756 (define-condition join-thread-error (error)
757 ((thread :reader join-thread-error-thread :initarg :thread))
759 (:documentation "Joining thread failed.")
760 (:report (lambda (c s)
761 (format s "Joining thread failed: thread ~A ~
762 has not returned normally."
763 (join-thread-error-thread c)))))
766 (setf (fdocumentation 'join-thread-error-thread 'function)
767 "The thread that we failed to join.")
769 (defun join-thread (thread &key (default nil defaultp))
771 "Suspend current thread until THREAD exits. Returns the result
772 values of the thread function. If the thread does not exit normally,
773 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
774 (with-mutex ((thread-result-lock thread))
775 (cond ((car (thread-result thread))
776 (values-list (cdr (thread-result thread))))
780 (error 'join-thread-error :thread thread)))))
782 (defun destroy-thread (thread)
784 "Deprecated. Same as TERMINATE-THREAD."
785 (terminate-thread thread))
787 (define-condition interrupt-thread-error (error)
788 ((thread :reader interrupt-thread-error-thread :initarg :thread))
790 (:documentation "Interrupting thread failed.")
791 (:report (lambda (c s)
792 (format s "Interrupt thread failed: thread ~A has exited."
793 (interrupt-thread-error-thread c)))))
796 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
797 "The thread that was not interrupted.")
799 (defmacro with-interruptions-lock ((thread) &body body)
800 `(with-system-mutex ((thread-interruptions-lock ,thread))
803 ;; Called from the signal handler in C.
804 (defun run-interruption ()
807 (let ((interruption (with-interruptions-lock (*current-thread*)
808 (pop (thread-interruptions *current-thread*)))))
811 (funcall interruption))
814 ;; The order of interrupt execution is peculiar. If thread A
815 ;; interrupts thread B with I1, I2 and B for some reason receives I1
816 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
817 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
818 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
819 ;; just one scenario, and the order of thread interrupt execution is
821 (defun interrupt-thread (thread function)
823 "Interrupt the live THREAD and make it run FUNCTION. A moderate
824 degree of care is expected for use of INTERRUPT-THREAD, due to its
825 nature: if you interrupt a thread that was holding important locks
826 then do something that turns out to need those locks, you probably
827 won't like the effect."
828 #!-sb-thread (declare (ignore thread))
830 (with-interrupt-bindings
831 (with-interrupts (funcall function)))
833 (if (eq thread *current-thread*)
834 (with-interrupt-bindings
835 (with-interrupts (funcall function)))
836 (let ((os-thread (thread-os-thread thread)))
837 (cond ((not os-thread)
838 (error 'interrupt-thread-error :thread thread))
840 (with-interruptions-lock (thread)
841 (push function (thread-interruptions thread)))
842 (when (minusp (signal-interrupt-thread os-thread))
843 (error 'interrupt-thread-error :thread thread)))))))
845 (defun terminate-thread (thread)
847 "Terminate the thread identified by THREAD, by causing it to run
848 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
849 (interrupt-thread thread 'sb!ext:quit))
851 (define-alien-routine "thread_yield" int)
854 (setf (fdocumentation 'thread-yield 'function)
855 "Yield the processor to other threads.")
857 ;;; internal use only. If you think you need to use these, either you
858 ;;; are an SBCL developer, are doing something that you should discuss
859 ;;; with an SBCL developer first, or are doing something that you
860 ;;; should probably discuss with a professional psychiatrist first
863 (defun %thread-sap (thread)
864 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
865 (target (thread-os-thread thread)))
867 (when (sap= thread-sap (int-sap 0)) (return nil))
868 (let ((os-thread (sap-ref-word thread-sap
869 (* sb!vm:n-word-bytes
870 sb!vm::thread-os-thread-slot))))
871 (when (= os-thread target) (return thread-sap))
873 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
874 sb!vm::thread-next-slot)))))))
876 (defun %symbol-value-in-thread (symbol thread)
878 ;; Prevent the dead from dying completely while we look for the TLS area...
879 (with-all-threads-lock
880 (if (thread-alive-p thread)
881 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
882 (tl-val (sap-ref-word (%thread-sap thread) offset)))
883 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
885 (return-from %symbol-value-in-thread (values (make-lisp-obj tl-val) t))))
886 (return-from %symbol-value-in-thread (values nil nil))))
888 (error "Cannot read thread-local symbol value: ~S unbound in ~S" symbol thread)))
890 (defun %set-symbol-value-in-thread (symbol thread value)
892 (with-pinned-objects (value)
893 ;; Prevent the dead from dying completely while we look for the TLS area...
894 (with-all-threads-lock
895 (if (thread-alive-p thread)
896 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
897 (sap (%thread-sap thread))
898 (tl-val (sap-ref-word sap offset)))
899 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
901 (setf (sap-ref-word sap offset) (get-lisp-obj-address value)))
902 (return-from %set-symbol-value-in-thread (values value t)))
903 (return-from %set-symbol-value-in-thread (values nil nil)))))
905 (error "Cannot set thread-local symbol value: ~S unbound in ~S" symbol thread))))
907 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
908 (sb!vm::locked-symbol-global-value-add symbol-name delta))
912 (defun thread-stepping ()
914 (sap-ref-word (current-thread-sap)
915 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
917 (defun (setf thread-stepping) (value)
918 (setf (sap-ref-word (current-thread-sap)
919 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
920 (get-lisp-obj-address value)))