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 `(call-with-system-mutex (lambda () ,@body) *all-threads-lock*))
65 (defun list-all-threads ()
67 "Return a list of the live threads."
68 (with-all-threads-lock
69 (copy-list *all-threads*)))
71 (declaim (inline current-thread-sap))
72 (defun current-thread-sap ()
73 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
75 (declaim (inline current-thread-sap-id))
76 (defun current-thread-sap-id ()
78 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
80 (defun init-initial-thread ()
81 (/show0 "Entering INIT-INITIAL-THREAD")
82 (let ((initial-thread (%make-thread :name "initial thread"
84 :os-thread (current-thread-sap-id))))
85 (setq *current-thread* initial-thread)
86 ;; Either *all-threads* is empty or it contains exactly one thread
87 ;; in case we are in reinit since saving core with multiple
88 ;; threads doesn't work.
89 (setq *all-threads* (list initial-thread))))
95 ;; FIXME it would be good to define what a thread id is or isn't
96 ;; (our current assumption is that it's a fixnum). It so happens
97 ;; that on Linux it's a pid, but it might not be on posix thread
99 (define-alien-routine ("create_thread" %create-thread)
100 unsigned-long (lisp-fun-address unsigned-long))
102 (define-alien-routine "signal_interrupt_thread"
103 integer (os-thread unsigned-long))
105 (define-alien-routine "block_deferrable_signals"
110 (declaim (inline %lutex-init %lutex-wait %lutex-wake
111 %lutex-lock %lutex-unlock))
113 (define-alien-routine ("lutex_init" %lutex-init)
114 int (lutex unsigned-long))
116 (define-alien-routine ("lutex_wait" %lutex-wait)
117 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
119 (define-alien-routine ("lutex_wake" %lutex-wake)
120 int (lutex unsigned-long) (n int))
122 (define-alien-routine ("lutex_lock" %lutex-lock)
123 int (lutex unsigned-long))
125 (define-alien-routine ("lutex_trylock" %lutex-trylock)
126 int (lutex unsigned-long))
128 (define-alien-routine ("lutex_unlock" %lutex-unlock)
129 int (lutex unsigned-long))
131 (define-alien-routine ("lutex_destroy" %lutex-destroy)
132 int (lutex unsigned-long))
134 ;; FIXME: Defining a whole bunch of alien-type machinery just for
135 ;; passing primitive lutex objects directly to foreign functions
136 ;; doesn't seem like fun right now. So instead we just manually
137 ;; pin the lutex, get its address, and let the callee untag it.
138 (defmacro with-lutex-address ((name lutex) &body body)
139 `(let ((,name ,lutex))
140 (with-pinned-objects (,name)
141 (let ((,name (get-lisp-obj-address ,name)))
145 (/show0 "Entering MAKE-LUTEX")
146 ;; Suppress GC until the lutex has been properly registered with
149 (let ((lutex (sb!vm::%make-lutex)))
152 (with-lutex-address (lutex lutex)
158 (declaim (inline futex-wait %futex-wait futex-wake))
160 (define-alien-routine ("futex_wait" %futex-wait)
161 int (word unsigned-long) (old-value unsigned-long)
162 (to-sec long) (to-usec unsigned-long))
164 (defun futex-wait (word old to-sec to-usec)
166 (%futex-wait word old to-sec to-usec)))
168 (define-alien-routine "futex_wake"
169 int (word unsigned-long) (n unsigned-long))))
171 ;;; used by debug-int.lisp to access interrupt contexts
172 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
174 (defun sb!vm::current-thread-offset-sap (n)
175 (declare (type (unsigned-byte 27) n))
176 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
177 (* n sb!vm:n-word-bytes)))
180 (defun sb!vm::current-thread-offset-sap (n)
181 (declare (type (unsigned-byte 27) n))
182 (sb!vm::current-thread-offset-sap n))
185 (define-structure-slot-compare-and-swap
186 compare-and-swap-spinlock-value
190 (declaim (inline get-spinlock release-spinlock))
192 ;; Should always be called with interrupts disabled.
193 (defun get-spinlock (spinlock)
194 (declare (optimize (speed 3) (safety 0)))
195 (let* ((new *current-thread*)
196 (old (compare-and-swap-spinlock-value spinlock nil new)))
199 (error "Recursive lock attempt on ~S." spinlock))
202 (unless (compare-and-swap-spinlock-value spinlock nil new)
203 (return-from get-spinlock t))))
204 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
205 ;; If interrupts are enabled, but we are allowed to enabled them,
206 ;; check for pending interrupts every once in a while.
208 (loop repeat 128 do (cas)) ; 128 is arbitrary here
209 (sb!unix::%check-interrupts))
213 (defun release-spinlock (spinlock)
214 (declare (optimize (speed 3) (safety 0)))
215 (setf (spinlock-value spinlock) nil)
221 (setf (fdocumentation 'make-mutex 'function)
223 (fdocumentation 'mutex-name 'function)
224 "The name of the mutex. Setfable."
225 (fdocumentation 'mutex-value 'function)
226 "The value of the mutex. NIL if the mutex is free. Setfable.")
228 #!+(and sb-thread (not sb-lutex))
230 (define-structure-slot-addressor mutex-value-address
233 (define-structure-slot-compare-and-swap
234 compare-and-swap-mutex-value
238 (defun get-mutex (mutex &optional (new-value *current-thread*) (waitp t))
240 "Acquire MUTEX, setting it to NEW-VALUE or some suitable default value if
241 NIL. If WAITP is non-NIL and the mutex is in use, sleep until it is available."
242 (declare (type mutex mutex) (optimize (speed 3)))
243 (/show0 "Entering GET-MUTEX")
245 (setq new-value *current-thread*))
247 (let ((old (mutex-value mutex)))
248 (when (and old waitp)
249 (error "In unithread mode, mutex ~S was requested with WAITP ~S and ~
250 new-value ~S, but has already been acquired (with value ~S)."
251 mutex waitp new-value old))
252 (setf (mutex-value mutex) new-value)
256 (when (eql new-value (mutex-value mutex))
257 (warn "recursive lock attempt ~S~%" mutex)
258 (format *debug-io* "Thread: ~A~%" *current-thread*)
259 (sb!debug:backtrace most-positive-fixnum *debug-io*)
260 (force-output *debug-io*))
261 ;; FIXME: Lutexes do not currently support deadlines, as at least
262 ;; on Darwin pthread_foo_timedbar functions are not supported:
263 ;; this means that we probably need to use the Carbon multiprocessing
264 ;; functions on Darwin.
266 ;; FIXME: This is definitely not interrupt safe: what happens if
267 ;; we get hit (1) during the lutex calls (ok, they may be safe,
268 ;; but has that been checked?) (2) after the lutex call, but
269 ;; before setting the mutex value.
271 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
273 (with-interrupts (%lutex-lock lutex))
274 (%lutex-trylock lutex))))
275 (setf (mutex-value mutex) new-value))
278 (when (and (setf old (compare-and-swap-mutex-value mutex nil new-value))
281 do (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
282 (when (= 1 (with-pinned-objects (mutex old)
283 (futex-wait (mutex-value-address mutex)
284 (get-lisp-obj-address old)
288 (setf old (compare-and-swap-mutex-value mutex nil new-value))))
291 (defun release-mutex (mutex)
293 "Release MUTEX by setting it to NIL. Wake up threads waiting for
295 (declare (type mutex mutex))
296 (/show0 "Entering RELEASE-MUTEX")
297 (setf (mutex-value mutex) nil)
301 (with-lutex-address (lutex (mutex-lutex mutex))
302 (%lutex-unlock lutex))
304 (futex-wake (mutex-value-address mutex) 1)))
306 ;;;; waitqueues/condition variables
308 (defstruct (waitqueue (:constructor %make-waitqueue))
311 (name nil :type (or null simple-string))
312 #!+(and sb-lutex sb-thread)
317 (defun make-waitqueue (&key name)
319 "Create a waitqueue."
320 (%make-waitqueue :name name))
323 (setf (fdocumentation 'waitqueue-name 'function)
324 "The name of the waitqueue. Setfable.")
326 #!+(and sb-thread (not sb-lutex))
327 (define-structure-slot-addressor waitqueue-data-address
331 (defun condition-wait (queue mutex)
333 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
334 thread may subsequently notify us using CONDITION-NOTIFY, at which
335 time we reacquire MUTEX and return to the caller."
336 #!-sb-thread (declare (ignore queue))
338 #!-sb-thread (error "Not supported in unithread builds.")
340 (let ((value (mutex-value mutex)))
341 (/show0 "CONDITION-WAITing")
344 ;; FIXME: This doesn't look interrupt safe!
345 (setf (mutex-value mutex) nil)
346 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
347 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
348 (%lutex-wait queue-lutex-address mutex-lutex-address)))
349 (setf (mutex-value mutex) value))
352 (let ((me *current-thread*))
353 ;; FIXME: should we do something to ensure that the result
354 ;; of this setf is visible to all CPUs?
355 (setf (waitqueue-data queue) me)
356 (release-mutex mutex)
357 ;; Now we go to sleep using futex-wait. If anyone else
358 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
359 ;; this comment, it will change queue->data, and so
360 ;; futex-wait returns immediately instead of sleeping.
361 ;; Ergo, no lost wakeup. We may get spurious wakeups,
363 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
364 (when (= 1 (with-pinned-objects (queue me)
365 (futex-wait (waitqueue-data-address queue)
366 (get-lisp-obj-address me)
367 (or to-sec -1) ;; our way if saying "no timeout"
370 ;; If we are interrupted while waiting, we should do these things
371 ;; before returning. Ideally, in the case of an unhandled signal,
372 ;; we should do them before entering the debugger, but this is
373 ;; better than nothing.
374 (get-mutex mutex value))))
376 (defun condition-notify (queue &optional (n 1))
378 "Notify N threads waiting on QUEUE."
379 #!-sb-thread (declare (ignore queue n))
380 #!-sb-thread (error "Not supported in unithread builds.")
382 (declare (type (and fixnum (integer 1)) n))
383 (/show0 "Entering CONDITION-NOTIFY")
387 (with-lutex-address (lutex (waitqueue-lutex queue))
388 (%lutex-wake lutex n))
389 ;; no problem if >1 thread notifies during the comment in
390 ;; condition-wait: as long as the value in queue-data isn't the
391 ;; waiting thread's id, it matters not what it is
392 ;; XXX we should do something to ensure that the result of this setf
393 ;; is visible to all CPUs
395 (let ((me *current-thread*))
397 (setf (waitqueue-data queue) me)
398 (with-pinned-objects (queue)
399 (futex-wake (waitqueue-data-address queue) n))))))
401 (defun condition-broadcast (queue)
403 "Notify all threads waiting on QUEUE."
404 (condition-notify queue
405 ;; On a 64-bit platform truncating M-P-F to an int results
406 ;; in -1, which wakes up only one thread.
408 most-positive-fixnum)))
412 (defstruct (semaphore (:constructor %make-semaphore))
415 (name nil :type (or null simple-string))
416 (count 0 :type (integer 0))
418 (queue (make-waitqueue)))
420 (defun make-semaphore (&key name (count 0))
422 "Create a semaphore with the supplied COUNT."
423 (%make-semaphore :name name :count count))
425 (setf (fdocumentation 'semaphore-name 'function)
426 "The name of the semaphore. Setfable.")
428 (defun wait-on-semaphore (sem)
430 "Decrement the count of SEM if the count would not be negative. Else
431 block until the semaphore can be decremented."
432 ;; a more direct implementation based directly on futexes should be
434 (with-mutex ((semaphore-mutex sem))
435 (loop until (> (semaphore-count sem) 0)
436 do (condition-wait (semaphore-queue sem) (semaphore-mutex sem))
437 finally (decf (semaphore-count sem)))))
439 (defun signal-semaphore (sem &optional (n 1))
441 "Increment the count of SEM by N. If there are threads waiting on
442 this semaphore, then N of them is woken up."
443 (declare (type (and fixnum (integer 1)) n))
444 (with-mutex ((semaphore-mutex sem))
445 (when (= n (incf (semaphore-count sem) n))
446 (condition-notify (semaphore-queue sem) n))))
448 ;;;; job control, independent listeners
451 (lock (make-mutex :name "session lock"))
453 (interactive-threads nil)
454 (interactive-threads-queue (make-waitqueue)))
456 (defvar *session* nil)
458 ;;; the debugger itself tries to acquire the session lock, don't let
459 ;;; funny situations (like getting a sigint while holding the session
461 (defmacro with-session-lock ((session) &body body)
462 `(call-with-system-mutex (lambda () ,@body) (session-lock ,session)))
464 (defun new-session ()
465 (make-session :threads (list *current-thread*)
466 :interactive-threads (list *current-thread*)))
468 (defun init-job-control ()
469 (/show0 "Entering INIT-JOB-CONTROL")
470 (setf *session* (new-session))
471 (/show0 "Exiting INIT-JOB-CONTROL"))
473 (defun %delete-thread-from-session (thread session)
474 (with-session-lock (session)
475 (setf (session-threads session)
476 (delete thread (session-threads session))
477 (session-interactive-threads session)
478 (delete thread (session-interactive-threads session)))))
480 (defun call-with-new-session (fn)
481 (%delete-thread-from-session *current-thread* *session*)
482 (let ((*session* (new-session)))
485 (defmacro with-new-session (args &body forms)
486 (declare (ignore args)) ;for extensibility
487 (sb!int:with-unique-names (fb-name)
488 `(labels ((,fb-name () ,@forms))
489 (call-with-new-session (function ,fb-name)))))
491 ;;; Remove thread from its session, if it has one.
493 (defun handle-thread-exit (thread)
494 (/show0 "HANDLING THREAD EXIT")
495 ;; We're going down, can't handle interrupts sanely anymore.
496 ;; GC remains enabled.
497 (block-deferrable-signals)
499 (with-all-threads-lock
500 (setf (thread-%alive-p thread) nil)
501 (setf (thread-os-thread thread) nil)
502 (setq *all-threads* (delete thread *all-threads*))
504 (%delete-thread-from-session thread *session*)))
507 (/show0 "FREEING MUTEX LUTEX")
508 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
509 (%lutex-destroy lutex))))
511 (defun terminate-session ()
513 "Kill all threads in session except for this one. Does nothing if current
514 thread is not the foreground thread."
515 ;; FIXME: threads created in other threads may escape termination
517 (with-session-lock (*session*)
518 (and (eq *current-thread*
519 (car (session-interactive-threads *session*)))
520 (session-threads *session*)))))
521 ;; do the kill after dropping the mutex; unwind forms in dying
522 ;; threads may want to do session things
523 (dolist (thread to-kill)
524 (unless (eq thread *current-thread*)
525 ;; terminate the thread but don't be surprised if it has
526 ;; exited in the meantime
527 (handler-case (terminate-thread thread)
528 (interrupt-thread-error ()))))))
530 ;;; called from top of invoke-debugger
531 (defun debugger-wait-until-foreground-thread (stream)
532 "Returns T if thread had been running in background, NIL if it was
534 (declare (ignore stream))
538 (with-session-lock (*session*)
539 (not (member *current-thread*
540 (session-interactive-threads *session*))))
543 (defun get-foreground ()
546 (let ((was-foreground t))
548 (/show0 "Looping in GET-FOREGROUND")
549 (with-session-lock (*session*)
550 (let ((int-t (session-interactive-threads *session*)))
551 (when (eq (car int-t) *current-thread*)
552 (unless was-foreground
553 (format *query-io* "Resuming thread ~A~%" *current-thread*))
554 (return-from get-foreground t))
555 (setf was-foreground nil)
556 (unless (member *current-thread* int-t)
557 (setf (cdr (last int-t))
558 (list *current-thread*)))
560 (session-interactive-threads-queue *session*)
561 (session-lock *session*)))))))
563 (defun release-foreground (&optional next)
565 "Background this thread. If NEXT is supplied, arrange for it to
566 have the foreground next."
567 #!-sb-thread (declare (ignore next))
570 (with-session-lock (*session*)
571 (when (rest (session-interactive-threads *session*))
572 (setf (session-interactive-threads *session*)
573 (delete *current-thread* (session-interactive-threads *session*))))
575 (setf (session-interactive-threads *session*)
577 (delete next (session-interactive-threads *session*)))))
578 (condition-broadcast (session-interactive-threads-queue *session*))))
580 (defun foreground-thread ()
581 (car (session-interactive-threads *session*)))
583 (defun make-listener-thread (tty-name)
584 (assert (probe-file tty-name))
585 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
586 (out (sb!unix:unix-dup in))
587 (err (sb!unix:unix-dup in)))
588 (labels ((thread-repl ()
589 (sb!unix::unix-setsid)
590 (let* ((sb!impl::*stdin*
591 (make-fd-stream in :input t :buffering :line
594 (make-fd-stream out :output t :buffering :line
597 (make-fd-stream err :output t :buffering :line
600 (make-fd-stream err :input t :output t
603 (sb!impl::*descriptor-handlers* nil))
606 (sb!impl::toplevel-repl nil)
607 (sb!int:flush-standard-output-streams))))))
608 (make-thread #'thread-repl))))
612 (defun make-thread (function &key name)
614 "Create a new thread of NAME that runs FUNCTION. When the function
615 returns the thread exits. The return values of FUNCTION are kept
616 around and can be retrieved by JOIN-THREAD."
617 #!-sb-thread (declare (ignore function name))
618 #!-sb-thread (error "Not supported in unithread builds.")
620 (let* ((thread (%make-thread :name name))
621 (setup-sem (make-semaphore :name "Thread setup semaphore"))
622 (real-function (coerce function 'function))
625 ;; In time we'll move some of the binding presently done in C
628 ;; KLUDGE: Here we have a magic list of variables that are
629 ;; not thread-safe for one reason or another. As people
630 ;; report problems with the thread safety of certain
631 ;; variables, (e.g. "*print-case* in multiple threads
632 ;; broken", sbcl-devel 2006-07-14), we add a few more
633 ;; bindings here. The Right Thing is probably some variant
634 ;; of Allegro's *cl-default-special-bindings*, as that is at
635 ;; least accessible to users to secure their own libraries.
637 (let ((*current-thread* thread)
638 (*restart-clusters* nil)
639 (*handler-clusters* nil)
640 (*condition-restarts* nil)
641 (sb!impl::*step-out* nil)
642 ;; internal printer variables
643 (sb!impl::*previous-case* nil)
644 (sb!impl::*previous-readtable-case* nil)
645 (sb!impl::*merge-sort-temp-vector* (vector)) ; keep these small!
646 (sb!impl::*zap-array-data-temp* (vector)) ;
647 (sb!impl::*internal-symbol-output-fun* nil)
648 (sb!impl::*descriptor-handlers* nil)) ; serve-event
649 (setf (thread-os-thread thread) (current-thread-sap-id))
650 (with-mutex ((thread-result-lock thread))
651 (with-all-threads-lock
652 (push thread *all-threads*))
653 (with-session-lock (*session*)
654 (push thread (session-threads *session*)))
655 (setf (thread-%alive-p thread) t)
656 (signal-semaphore setup-sem)
657 ;; can't use handling-end-of-the-world, because that flushes
658 ;; output streams, and we don't necessarily have any (or we
659 ;; could be sharing them)
660 (catch 'sb!impl::toplevel-catcher
661 (catch 'sb!impl::%end-of-the-world
665 "~~@<Terminate this thread (~A)~~@:>"
669 ;; now that most things have a chance to
670 ;; work properly without messing up other
671 ;; threads, it's time to enable signals
672 (sb!unix::reset-signal-mask)
673 (setf (thread-result thread)
676 (funcall real-function)))))
677 (handle-thread-exit thread)))))))
679 ;; Keep INITIAL-FUNCTION pinned until the child thread is
680 ;; initialized properly.
681 (with-pinned-objects (initial-function)
684 (get-lisp-obj-address initial-function))))
685 (when (zerop os-thread)
686 (error "Can't create a new thread"))
687 (wait-on-semaphore setup-sem)
690 (define-condition join-thread-error (error)
691 ((thread :reader join-thread-error-thread :initarg :thread))
693 (:documentation "Joining thread failed.")
694 (:report (lambda (c s)
695 (format s "Joining thread failed: thread ~A ~
696 has not returned normally."
697 (join-thread-error-thread c)))))
700 (setf (fdocumentation 'join-thread-error-thread 'function)
701 "The thread that we failed to join.")
703 (defun join-thread (thread &key (default nil defaultp))
705 "Suspend current thread until THREAD exits. Returns the result
706 values of the thread function. If the thread does not exit normally,
707 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
708 (with-mutex ((thread-result-lock thread))
709 (cond ((car (thread-result thread))
710 (values-list (cdr (thread-result thread))))
714 (error 'join-thread-error :thread thread)))))
716 (defun destroy-thread (thread)
718 "Deprecated. Same as TERMINATE-THREAD."
719 (terminate-thread thread))
721 (define-condition interrupt-thread-error (error)
722 ((thread :reader interrupt-thread-error-thread :initarg :thread))
724 (:documentation "Interrupting thread failed.")
725 (:report (lambda (c s)
726 (format s "Interrupt thread failed: thread ~A has exited."
727 (interrupt-thread-error-thread c)))))
730 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
731 "The thread that was not interrupted.")
733 (defmacro with-interruptions-lock ((thread) &body body)
734 `(call-with-system-mutex (lambda () ,@body) (thread-interruptions-lock ,thread)))
736 ;; Called from the signal handler in C.
737 (defun run-interruption ()
740 (let ((interruption (with-interruptions-lock (*current-thread*)
741 (pop (thread-interruptions *current-thread*)))))
744 (funcall interruption))
747 ;; The order of interrupt execution is peculiar. If thread A
748 ;; interrupts thread B with I1, I2 and B for some reason receives I1
749 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
750 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
751 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
752 ;; just one scenario, and the order of thread interrupt execution is
754 (defun interrupt-thread (thread function)
756 "Interrupt the live THREAD and make it run FUNCTION. A moderate
757 degree of care is expected for use of INTERRUPT-THREAD, due to its
758 nature: if you interrupt a thread that was holding important locks
759 then do something that turns out to need those locks, you probably
760 won't like the effect."
761 #!-sb-thread (declare (ignore thread))
763 (with-interrupt-bindings
764 (with-interrupts (funcall function)))
766 (if (eq thread *current-thread*)
767 (with-interrupt-bindings
768 (with-interrupts (funcall function)))
769 (let ((os-thread (thread-os-thread thread)))
770 (cond ((not os-thread)
771 (error 'interrupt-thread-error :thread thread))
773 (with-interruptions-lock (thread)
774 (push function (thread-interruptions thread)))
775 (when (minusp (signal-interrupt-thread os-thread))
776 (error 'interrupt-thread-error :thread thread)))))))
778 (defun terminate-thread (thread)
780 "Terminate the thread identified by THREAD, by causing it to run
781 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
782 (interrupt-thread thread 'sb!ext:quit))
784 ;;; internal use only. If you think you need to use this, either you
785 ;;; are an SBCL developer, are doing something that you should discuss
786 ;;; with an SBCL developer first, or are doing something that you
787 ;;; should probably discuss with a professional psychiatrist first
789 (defun thread-sap-for-id (id)
790 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
792 (when (sap= thread-sap (int-sap 0)) (return nil))
793 (let ((os-thread (sap-ref-word thread-sap
794 (* sb!vm:n-word-bytes
795 sb!vm::thread-os-thread-slot))))
796 (when (= os-thread id) (return thread-sap))
798 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
799 sb!vm::thread-next-slot)))))))
802 (defun symbol-value-in-thread (symbol thread-sap)
803 (let* ((index (sb!vm::symbol-tls-index symbol))
804 (tl-val (sap-ref-word thread-sap
805 (* sb!vm:n-word-bytes index))))
806 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
807 (sb!vm::symbol-global-value symbol)
808 (make-lisp-obj tl-val))))
810 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
811 (sb!vm::locked-symbol-global-value-add symbol-name delta))
815 (defun thread-stepping ()
817 (sap-ref-word (current-thread-sap)
818 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
820 (defun (setf thread-stepping) (value)
821 (setf (sap-ref-word (current-thread-sap)
822 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
823 (get-lisp-obj-address value)))