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)
47 (join-thread thread :default cookie))))
48 (state (if (eq :running info)
50 (if (eq cookie (car info))
53 (values (when (eq :finished state) info)))
55 "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
61 (defun thread-alive-p (thread)
63 "Check if THREAD is running."
64 (thread-%alive-p thread))
66 ;; A thread is eligible for gc iff it has finished and there are no
67 ;; more references to it. This list is supposed to keep a reference to
68 ;; all running threads.
69 (defvar *all-threads* ())
70 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
72 (defvar *default-alloc-signal* nil)
74 (defmacro with-all-threads-lock (&body body)
75 `(with-system-mutex (*all-threads-lock*)
78 (defun list-all-threads ()
80 "Return a list of the live threads."
81 (with-all-threads-lock
82 (copy-list *all-threads*)))
84 (declaim (inline current-thread-sap))
85 (defun current-thread-sap ()
86 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
88 (declaim (inline current-thread-os-thread))
89 (defun current-thread-os-thread ()
91 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
93 (defun init-initial-thread ()
94 (/show0 "Entering INIT-INITIAL-THREAD")
95 (let ((initial-thread (%make-thread :name "initial thread"
97 :os-thread (current-thread-os-thread))))
98 (setq *current-thread* initial-thread)
99 ;; Either *all-threads* is empty or it contains exactly one thread
100 ;; in case we are in reinit since saving core with multiple
101 ;; threads doesn't work.
102 (setq *all-threads* (list initial-thread))))
105 ;;;; Aliens, low level stuff
109 ;; FIXME it would be good to define what a thread id is or isn't
110 ;; (our current assumption is that it's a fixnum). It so happens
111 ;; that on Linux it's a pid, but it might not be on posix thread
113 (define-alien-routine ("create_thread" %create-thread)
114 unsigned-long (lisp-fun-address unsigned-long))
116 (define-alien-routine "signal_interrupt_thread"
117 integer (os-thread unsigned-long))
119 (define-alien-routine "block_deferrable_signals"
124 (declaim (inline %lutex-init %lutex-wait %lutex-wake
125 %lutex-lock %lutex-unlock))
127 (define-alien-routine ("lutex_init" %lutex-init)
128 int (lutex unsigned-long))
130 (define-alien-routine ("lutex_wait" %lutex-wait)
131 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
133 (define-alien-routine ("lutex_wake" %lutex-wake)
134 int (lutex unsigned-long) (n int))
136 (define-alien-routine ("lutex_lock" %lutex-lock)
137 int (lutex unsigned-long))
139 (define-alien-routine ("lutex_trylock" %lutex-trylock)
140 int (lutex unsigned-long))
142 (define-alien-routine ("lutex_unlock" %lutex-unlock)
143 int (lutex unsigned-long))
145 (define-alien-routine ("lutex_destroy" %lutex-destroy)
146 int (lutex unsigned-long))
148 ;; FIXME: Defining a whole bunch of alien-type machinery just for
149 ;; passing primitive lutex objects directly to foreign functions
150 ;; doesn't seem like fun right now. So instead we just manually
151 ;; pin the lutex, get its address, and let the callee untag it.
152 (defmacro with-lutex-address ((name lutex) &body body)
153 `(let ((,name ,lutex))
154 (with-pinned-objects (,name)
155 (let ((,name (get-lisp-obj-address ,name)))
159 (/show0 "Entering MAKE-LUTEX")
160 ;; Suppress GC until the lutex has been properly registered with
163 (let ((lutex (sb!vm::%make-lutex)))
166 (with-lutex-address (lutex lutex)
172 (declaim (inline futex-wait %futex-wait futex-wake))
174 (define-alien-routine ("futex_wait" %futex-wait)
175 int (word unsigned-long) (old-value unsigned-long)
176 (to-sec long) (to-usec unsigned-long))
178 (defun futex-wait (word old to-sec to-usec)
180 (%futex-wait word old to-sec to-usec)))
182 (define-alien-routine "futex_wake"
183 int (word unsigned-long) (n unsigned-long))))
185 ;;; used by debug-int.lisp to access interrupt contexts
186 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
188 (defun sb!vm::current-thread-offset-sap (n)
189 (declare (type (unsigned-byte 27) n))
190 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
191 (* n sb!vm:n-word-bytes)))
194 (defun sb!vm::current-thread-offset-sap (n)
195 (declare (type (unsigned-byte 27) n))
196 (sb!vm::current-thread-offset-sap n))
201 (declaim (inline get-spinlock release-spinlock))
203 ;;; Should always be called with interrupts disabled.
204 (defun get-spinlock (spinlock)
205 (declare (optimize (speed 3) (safety 0)))
206 (let* ((new *current-thread*)
207 (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
210 (error "Recursive lock attempt on ~S." spinlock))
213 (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
215 (return-from get-spinlock t))))
216 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
217 ;; If interrupts are enabled, but we are allowed to enabled them,
218 ;; check for pending interrupts every once in a while.
220 (loop repeat 128 do (cas)) ; 128 is arbitrary here
221 (sb!unix::%check-interrupts))
225 (defun release-spinlock (spinlock)
226 (declare (optimize (speed 3) (safety 0)))
227 ;; On x86 and x86-64 we can get away with no memory barriers, (see
228 ;; Linux kernel mailing list "spin_unlock optimization(i386)"
229 ;; thread, summary at
230 ;; http://kt.iserv.nl/kernel-traffic/kt19991220_47.html#1.
232 ;; If the compiler may reorder this with other instructions, insert
233 ;; compiler barrier here.
235 ;; FIXME: this does not work on SMP Pentium Pro and OOSTORE systems,
236 ;; neither on most non-x86 architectures (but we don't have threads
238 (setf (spinlock-value spinlock) nil))
244 (setf (fdocumentation 'make-mutex 'function)
246 (fdocumentation 'mutex-name 'function)
247 "The name of the mutex. Setfable.")
249 #!+(and sb-thread (not sb-lutex))
251 (define-structure-slot-addressor mutex-state-address
254 ;; Important: current code assumes these are fixnums or other
255 ;; lisp objects that don't need pinning.
256 (defconstant +lock-free+ 0)
257 (defconstant +lock-taken+ 1)
258 (defconstant +lock-contested+ 2))
260 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
262 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
263 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
264 non-NIL and the mutex is in use, sleep until it is available.
266 Note: using GET-MUTEX to assign a MUTEX to another thread then the
267 current one is not recommended, and liable to be deprecated.
269 GET-MUTEX is not interrupt safe. The correct way to call it is:
273 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
276 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
277 call while the mutex is in an inconsistent state while
278 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
280 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
282 (declare (type mutex mutex) (optimize (speed 3))
283 #!-sb-thread (ignore waitp))
285 (setq new-owner *current-thread*))
286 (let ((old (mutex-%owner mutex)))
287 (when (eq new-owner old)
288 (error "Recursive lock attempt ~S." mutex))
291 (error "Strange deadlock on ~S in an unithreaded build?" mutex)
292 (setf (mutex-%owner mutex) new-owner)))
295 ;; FIXME: Lutexes do not currently support deadlines, as at least
296 ;; on Darwin pthread_foo_timedbar functions are not supported:
297 ;; this means that we probably need to use the Carbon multiprocessing
298 ;; functions on Darwin.
300 ;; FIXME: This is definitely not interrupt safe: what happens if
301 ;; we get hit (1) during the lutex calls (ok, they may be safe,
302 ;; but has that been checked?) (2) after the lutex call, but
303 ;; before setting the mutex owner.
305 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
307 (with-interrupts (%lutex-lock lutex))
308 (%lutex-trylock lutex))))
309 (setf (mutex-%owner mutex) new-owner)
312 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
315 (unless (or (eql +lock-free+ old) (not waitp))
318 (when (or (eql +lock-contested+ old)
319 (not (eql +lock-free+
320 (sb!ext:compare-and-swap (mutex-state mutex)
323 ;; Wait on the contested lock.
324 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
325 (when (= 1 (with-pinned-objects (mutex)
326 (futex-wait (mutex-state-address mutex)
327 (get-lisp-obj-address +lock-contested+)
331 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
335 (unless (eql +lock-free+ old)
337 (cond ((eql +lock-free+ old)
338 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
341 (bug "Old owner in free mutex: ~S" prev))
344 (bug "Failed to acquire lock with WAITP."))))))
346 (defun release-mutex (mutex)
348 "Release MUTEX by setting it to NIL. Wake up threads waiting for
351 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
354 Signals a WARNING is current thread is not the current owner of the
356 (declare (type mutex mutex))
357 ;; Order matters: set owner to NIL before releasing state.
358 (let* ((self *current-thread*)
359 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
360 (unless (eql self old-owner)
361 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
362 (setf (mutex-%owner mutex) nil)))
366 (with-lutex-address (lutex (mutex-lutex mutex))
367 (%lutex-unlock lutex))
369 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
370 +lock-taken+ +lock-free+)))
371 (when (eql old +lock-contested+)
372 (sb!ext:compare-and-swap (mutex-state mutex)
373 +lock-contested+ +lock-free+)
374 (with-pinned-objects (mutex)
375 (futex-wake (mutex-state-address mutex) 1))))
379 ;;;; Waitqueues/condition variables
381 (defstruct (waitqueue (:constructor %make-waitqueue))
384 (name nil :type (or null simple-string))
385 #!+(and sb-lutex sb-thread)
390 (defun make-waitqueue (&key name)
392 "Create a waitqueue."
393 (%make-waitqueue :name name))
396 (setf (fdocumentation 'waitqueue-name 'function)
397 "The name of the waitqueue. Setfable.")
399 #!+(and sb-thread (not sb-lutex))
400 (define-structure-slot-addressor waitqueue-data-address
404 (defun condition-wait (queue mutex)
406 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
407 thread may subsequently notify us using CONDITION-NOTIFY, at which
408 time we reacquire MUTEX and return to the caller."
409 #!-sb-thread (declare (ignore queue))
411 #!-sb-thread (error "Not supported in unithread builds.")
413 (let ((me *current-thread*))
414 (assert (eq me (mutex-%owner mutex)))
415 (/show0 "CONDITION-WAITing")
417 ;; Need to disable interrupts so that we don't miss setting the
418 ;; owner on our way out. (pthread_cond_wait handles the actual
423 (setf (mutex-%owner mutex) nil)
424 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
425 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
426 (with-local-interrupts
427 (%lutex-wait queue-lutex-address mutex-lutex-address)))))
428 (setf (mutex-%owner mutex) me)))
430 ;; Need to disable interrupts so that we don't miss grabbing the
431 ;; mutex on our way out.
434 (let ((me *current-thread*))
435 ;; This setf becomes visible to other CPUS due to the
436 ;; usual memory barrier semantics of lock
438 (setf (waitqueue-data queue) me)
439 (release-mutex mutex)
440 ;; Now we go to sleep using futex-wait. If anyone else
441 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
442 ;; this comment, it will change queue->data, and so
443 ;; futex-wait returns immediately instead of sleeping.
444 ;; Ergo, no lost wakeup. We may get spurious wakeups, but
446 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
447 (when (= 1 (with-pinned-objects (queue me)
448 (allow-with-interrupts
449 (futex-wait (waitqueue-data-address queue)
450 (get-lisp-obj-address me)
451 ;; our way if saying "no
456 ;; If we are interrupted while waiting, we should do these
457 ;; things before returning. Ideally, in the case of an
458 ;; unhandled signal, we should do them before entering the
459 ;; debugger, but this is better than nothing.
460 (get-mutex mutex)))))
462 (defun condition-notify (queue &optional (n 1))
464 "Notify N threads waiting on QUEUE. The same mutex that is used in
465 the correspoinding condition-wait must be held by this thread during
467 #!-sb-thread (declare (ignore queue n))
468 #!-sb-thread (error "Not supported in unithread builds.")
470 (declare (type (and fixnum (integer 1)) n))
471 (/show0 "Entering CONDITION-NOTIFY")
475 (with-lutex-address (lutex (waitqueue-lutex queue))
476 (%lutex-wake lutex n))
477 ;; no problem if >1 thread notifies during the comment in
478 ;; condition-wait: as long as the value in queue-data isn't the
479 ;; waiting thread's id, it matters not what it is
480 ;; XXX we should do something to ensure that the result of this setf
481 ;; is visible to all CPUs
483 (let ((me *current-thread*))
485 (setf (waitqueue-data queue) me)
486 (with-pinned-objects (queue)
487 (futex-wake (waitqueue-data-address queue) n))))))
489 (defun condition-broadcast (queue)
491 "Notify all threads waiting on QUEUE."
492 (condition-notify queue
493 ;; On a 64-bit platform truncating M-P-F to an int
494 ;; results in -1, which wakes up only one thread.
496 most-positive-fixnum)))
501 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
503 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
504 should be considered an implementation detail, and may change in the
506 (name nil :type (or null simple-string))
507 (%count 0 :type (integer 0))
508 (waitcount 0 :type (integer 0))
510 (queue (make-waitqueue)))
512 (setf (fdocumentation 'semaphore-name 'function)
513 "The name of the semaphore INSTANCE. Setfable.")
515 (declaim (inline semaphore-count))
516 (defun semaphore-count (instance)
517 "Returns the current count of the semaphore INSTANCE."
518 (semaphore-%count instance))
520 (defun make-semaphore (&key name (count 0))
522 "Create a semaphore with the supplied COUNT and NAME."
523 (%make-semaphore name count))
525 (defun wait-on-semaphore (semaphore)
527 "Decrement the count of SEMAPHORE if the count would not be
528 negative. Else blocks until the semaphore can be decremented."
529 ;; A more direct implementation based directly on futexes should be
532 ;; We need to disable interrupts so that we don't forget to
533 ;; decrement the waitcount (which would happen if an asynch
534 ;; interrupt should catch us on our way out from the loop.)
535 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
536 ;; Quick check: is it positive? If not, enter the wait loop.
537 (let ((count (semaphore-%count semaphore)))
539 (setf (semaphore-%count semaphore) (1- count))
542 (incf (semaphore-waitcount semaphore))
543 (loop until (plusp (setf count (semaphore-%count semaphore)))
544 do (condition-wait (semaphore-queue semaphore)
545 (semaphore-mutex semaphore)))
546 (setf (semaphore-%count semaphore) (1- count)))
547 (decf (semaphore-waitcount semaphore)))))))
549 (defun signal-semaphore (semaphore &optional (n 1))
551 "Increment the count of SEMAPHORE by N. If there are threads waiting
552 on this semaphore, then N of them is woken up."
553 (declare (type (integer 1) n))
554 ;; Need to disable interrupts so that we don't lose a wakeup after
555 ;; we have incremented the count.
556 (with-system-mutex ((semaphore-mutex semaphore))
557 (let ((waitcount (semaphore-waitcount semaphore))
558 (count (incf (semaphore-%count semaphore) n)))
559 (when (plusp waitcount)
560 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
563 ;;;; Job control, independent listeners
566 (lock (make-mutex :name "session lock"))
568 (interactive-threads nil)
569 (interactive-threads-queue (make-waitqueue)))
571 (defvar *session* nil)
573 ;;; The debugger itself tries to acquire the session lock, don't let
574 ;;; funny situations (like getting a sigint while holding the session
575 ;;; lock) occur. At the same time we need to allow interrupts while
576 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
577 ;;; be interruptible.
579 ;;; Take care: we sometimes need to obtain the session lock while
580 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
581 ;;; _after_ getting a session lock! (Deadlock risk.)
583 ;;; FIXME: It would be good to have ordered locks to ensure invariants
585 (defmacro with-session-lock ((session) &body body)
586 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
589 (defun new-session ()
590 (make-session :threads (list *current-thread*)
591 :interactive-threads (list *current-thread*)))
593 (defun init-job-control ()
594 (/show0 "Entering INIT-JOB-CONTROL")
595 (setf *session* (new-session))
596 (/show0 "Exiting INIT-JOB-CONTROL"))
598 (defun %delete-thread-from-session (thread session)
599 (with-session-lock (session)
600 (setf (session-threads session)
601 (delete thread (session-threads session))
602 (session-interactive-threads session)
603 (delete thread (session-interactive-threads session)))))
605 (defun call-with-new-session (fn)
606 (%delete-thread-from-session *current-thread* *session*)
607 (let ((*session* (new-session)))
610 (defmacro with-new-session (args &body forms)
611 (declare (ignore args)) ;for extensibility
612 (sb!int:with-unique-names (fb-name)
613 `(labels ((,fb-name () ,@forms))
614 (call-with-new-session (function ,fb-name)))))
616 ;;; Remove thread from its session, if it has one.
618 (defun handle-thread-exit (thread)
619 (/show0 "HANDLING THREAD EXIT")
620 ;; We're going down, can't handle interrupts sanely anymore. GC
622 (block-deferrable-signals)
624 (with-all-threads-lock
625 (setf (thread-%alive-p thread) nil)
626 (setf (thread-os-thread thread) nil)
627 (setq *all-threads* (delete thread *all-threads*))
629 (%delete-thread-from-session thread *session*)))
632 (/show0 "FREEING MUTEX LUTEX")
633 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
634 (%lutex-destroy lutex))))
636 (defun terminate-session ()
638 "Kill all threads in session except for this one. Does nothing if current
639 thread is not the foreground thread."
640 ;; FIXME: threads created in other threads may escape termination
642 (with-session-lock (*session*)
643 (and (eq *current-thread*
644 (car (session-interactive-threads *session*)))
645 (session-threads *session*)))))
646 ;; do the kill after dropping the mutex; unwind forms in dying
647 ;; threads may want to do session things
648 (dolist (thread to-kill)
649 (unless (eq thread *current-thread*)
650 ;; terminate the thread but don't be surprised if it has
651 ;; exited in the meantime
652 (handler-case (terminate-thread thread)
653 (interrupt-thread-error ()))))))
655 ;;; called from top of invoke-debugger
656 (defun debugger-wait-until-foreground-thread (stream)
657 "Returns T if thread had been running in background, NIL if it was
659 (declare (ignore stream))
663 (with-session-lock (*session*)
664 (not (member *current-thread*
665 (session-interactive-threads *session*))))
668 (defun get-foreground ()
671 (let ((was-foreground t))
673 (/show0 "Looping in GET-FOREGROUND")
674 (with-session-lock (*session*)
675 (let ((int-t (session-interactive-threads *session*)))
676 (when (eq (car int-t) *current-thread*)
677 (unless was-foreground
678 (format *query-io* "Resuming thread ~A~%" *current-thread*))
679 (return-from get-foreground t))
680 (setf was-foreground nil)
681 (unless (member *current-thread* int-t)
682 (setf (cdr (last int-t))
683 (list *current-thread*)))
685 (session-interactive-threads-queue *session*)
686 (session-lock *session*)))))))
688 (defun release-foreground (&optional next)
690 "Background this thread. If NEXT is supplied, arrange for it to
691 have the foreground next."
692 #!-sb-thread (declare (ignore next))
695 (with-session-lock (*session*)
696 (when (rest (session-interactive-threads *session*))
697 (setf (session-interactive-threads *session*)
698 (delete *current-thread* (session-interactive-threads *session*))))
700 (setf (session-interactive-threads *session*)
702 (delete next (session-interactive-threads *session*)))))
703 (condition-broadcast (session-interactive-threads-queue *session*))))
705 (defun foreground-thread ()
706 (car (session-interactive-threads *session*)))
708 (defun make-listener-thread (tty-name)
709 (assert (probe-file tty-name))
710 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
711 (out (sb!unix:unix-dup in))
712 (err (sb!unix:unix-dup in)))
713 (labels ((thread-repl ()
714 (sb!unix::unix-setsid)
715 (let* ((sb!impl::*stdin*
716 (make-fd-stream in :input t :buffering :line
719 (make-fd-stream out :output t :buffering :line
722 (make-fd-stream err :output t :buffering :line
725 (make-fd-stream err :input t :output t
728 (sb!impl::*descriptor-handlers* nil))
731 (sb!impl::toplevel-repl nil)
732 (sb!int:flush-standard-output-streams))))))
733 (make-thread #'thread-repl))))
738 (defun make-thread (function &key name)
740 "Create a new thread of NAME that runs FUNCTION. When the function
741 returns the thread exits. The return values of FUNCTION are kept
742 around and can be retrieved by JOIN-THREAD."
743 #!-sb-thread (declare (ignore function name))
744 #!-sb-thread (error "Not supported in unithread builds.")
746 (let* ((thread (%make-thread :name name))
747 (setup-sem (make-semaphore :name "Thread setup semaphore"))
748 (real-function (coerce function 'function))
751 ;; In time we'll move some of the binding presently done in C
754 ;; KLUDGE: Here we have a magic list of variables that are
755 ;; not thread-safe for one reason or another. As people
756 ;; report problems with the thread safety of certain
757 ;; variables, (e.g. "*print-case* in multiple threads
758 ;; broken", sbcl-devel 2006-07-14), we add a few more
759 ;; bindings here. The Right Thing is probably some variant
760 ;; of Allegro's *cl-default-special-bindings*, as that is at
761 ;; least accessible to users to secure their own libraries.
763 (let* ((*current-thread* thread)
764 (*restart-clusters* nil)
765 (*handler-clusters* (sb!kernel::initial-handler-clusters))
766 (*condition-restarts* nil)
767 (sb!impl::*deadline* nil)
768 (sb!impl::*step-out* nil)
769 ;; internal printer variables
770 (sb!impl::*previous-case* nil)
771 (sb!impl::*previous-readtable-case* nil)
773 (sb!impl::*merge-sort-temp-vector* empty)
774 (sb!impl::*zap-array-data-temp* empty)
775 (sb!impl::*internal-symbol-output-fun* nil)
776 (sb!impl::*descriptor-handlers* nil)) ; serve-event
778 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
779 (setf (thread-os-thread thread) (current-thread-os-thread))
780 (with-mutex ((thread-result-lock thread))
781 (with-all-threads-lock
782 (push thread *all-threads*))
783 (with-session-lock (*session*)
784 (push thread (session-threads *session*)))
785 (setf (thread-%alive-p thread) t)
786 (signal-semaphore setup-sem)
787 ;; can't use handling-end-of-the-world, because that flushes
788 ;; output streams, and we don't necessarily have any (or we
789 ;; could be sharing them)
790 (catch 'sb!impl::toplevel-catcher
791 (catch 'sb!impl::%end-of-the-world
795 "~~@<Terminate this thread (~A)~~@:>"
799 ;; now that most things have a chance to
800 ;; work properly without messing up other
801 ;; threads, it's time to enable signals
802 (sb!unix::reset-signal-mask)
803 (setf (thread-result thread)
806 (funcall real-function)))))
807 (handle-thread-exit thread)))))))
809 ;; Keep INITIAL-FUNCTION pinned until the child thread is
810 ;; initialized properly.
811 (with-pinned-objects (initial-function)
814 (get-lisp-obj-address initial-function))))
815 (when (zerop os-thread)
816 (error "Can't create a new thread"))
817 (wait-on-semaphore setup-sem)
820 (define-condition join-thread-error (error)
821 ((thread :reader join-thread-error-thread :initarg :thread))
823 (:documentation "Joining thread failed.")
824 (:report (lambda (c s)
825 (format s "Joining thread failed: thread ~A ~
826 has not returned normally."
827 (join-thread-error-thread c)))))
830 (setf (fdocumentation 'join-thread-error-thread 'function)
831 "The thread that we failed to join.")
833 (defun join-thread (thread &key (default nil defaultp))
835 "Suspend current thread until THREAD exits. Returns the result
836 values of the thread function. If the thread does not exit normally,
837 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
838 (with-mutex ((thread-result-lock thread))
839 (cond ((car (thread-result thread))
840 (values-list (cdr (thread-result thread))))
844 (error 'join-thread-error :thread thread)))))
846 (defun destroy-thread (thread)
848 "Deprecated. Same as TERMINATE-THREAD."
849 (terminate-thread thread))
851 (define-condition interrupt-thread-error (error)
852 ((thread :reader interrupt-thread-error-thread :initarg :thread))
854 (:documentation "Interrupting thread failed.")
855 (:report (lambda (c s)
856 (format s "Interrupt thread failed: thread ~A has exited."
857 (interrupt-thread-error-thread c)))))
860 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
861 "The thread that was not interrupted.")
863 (defmacro with-interruptions-lock ((thread) &body body)
864 `(with-system-mutex ((thread-interruptions-lock ,thread))
867 ;;; Called from the signal handler in C.
868 (defun run-interruption ()
871 (let ((interruption (with-interruptions-lock (*current-thread*)
872 (pop (thread-interruptions *current-thread*)))))
875 (funcall interruption))
878 ;;; The order of interrupt execution is peculiar. If thread A
879 ;;; interrupts thread B with I1, I2 and B for some reason receives I1
880 ;;; when FUN2 is already on the list, then it is FUN2 that gets to run
881 ;;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
882 ;;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
883 ;;; just one scenario, and the order of thread interrupt execution is
885 (defun interrupt-thread (thread function)
887 "Interrupt the live THREAD and make it run FUNCTION. A moderate
888 degree of care is expected for use of INTERRUPT-THREAD, due to its
889 nature: if you interrupt a thread that was holding important locks
890 then do something that turns out to need those locks, you probably
891 won't like the effect."
892 #!-sb-thread (declare (ignore thread))
894 (with-interrupt-bindings
895 (with-interrupts (funcall function)))
897 (if (eq thread *current-thread*)
898 (with-interrupt-bindings
899 (with-interrupts (funcall function)))
900 (let ((os-thread (thread-os-thread thread)))
901 (cond ((not os-thread)
902 (error 'interrupt-thread-error :thread thread))
904 (with-interruptions-lock (thread)
905 (push function (thread-interruptions thread)))
906 (when (minusp (signal-interrupt-thread os-thread))
907 (error 'interrupt-thread-error :thread thread)))))))
909 (defun terminate-thread (thread)
911 "Terminate the thread identified by THREAD, by causing it to run
912 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
913 (interrupt-thread thread 'sb!ext:quit))
915 (define-alien-routine "thread_yield" int)
918 (setf (fdocumentation 'thread-yield 'function)
919 "Yield the processor to other threads.")
921 ;;; internal use only. If you think you need to use these, either you
922 ;;; are an SBCL developer, are doing something that you should discuss
923 ;;; with an SBCL developer first, or are doing something that you
924 ;;; should probably discuss with a professional psychiatrist first
927 (defun %thread-sap (thread)
928 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
929 (target (thread-os-thread thread)))
931 (when (sap= thread-sap (int-sap 0)) (return nil))
932 (let ((os-thread (sap-ref-word thread-sap
933 (* sb!vm:n-word-bytes
934 sb!vm::thread-os-thread-slot))))
935 (when (= os-thread target) (return thread-sap))
937 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
938 sb!vm::thread-next-slot)))))))
940 (defun %symbol-value-in-thread (symbol thread)
942 ;; Prevent the dead from dying completely while we look for the
944 (with-all-threads-lock
945 (if (thread-alive-p thread)
946 (let* ((offset (* sb!vm:n-word-bytes
947 (sb!vm::symbol-tls-index symbol)))
948 (tl-val (sap-ref-word (%thread-sap thread) offset)))
949 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
951 (return-from %symbol-value-in-thread
952 (values (make-lisp-obj tl-val) t))))
953 (return-from %symbol-value-in-thread (values nil nil))))
955 (error "Cannot read thread-local symbol value: ~S unbound in ~S"
958 (defun %set-symbol-value-in-thread (symbol thread value)
960 (with-pinned-objects (value)
961 ;; Prevent the dead from dying completely while we look for
963 (with-all-threads-lock
964 (if (thread-alive-p thread)
965 (let* ((offset (* sb!vm:n-word-bytes
966 (sb!vm::symbol-tls-index symbol)))
967 (sap (%thread-sap thread))
968 (tl-val (sap-ref-word sap offset)))
969 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
971 (setf (sap-ref-word sap offset)
972 (get-lisp-obj-address value)))
973 (return-from %set-symbol-value-in-thread (values value t)))
974 (return-from %set-symbol-value-in-thread (values nil nil)))))
976 (error "Cannot set thread-local symbol value: ~S unbound in ~S"
979 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
980 (sb!vm::locked-symbol-global-value-add symbol-name delta))
985 (defun thread-stepping ()
987 (sap-ref-word (current-thread-sap)
988 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
990 (defun (setf thread-stepping) (value)
991 (setf (sap-ref-word (current-thread-sap)
992 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
993 (get-lisp-obj-address value)))