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 (defvar *default-alloc-signal* nil)
72 (defmacro with-all-threads-lock (&body body)
73 `(with-system-mutex (*all-threads-lock*)
76 (defun list-all-threads ()
78 "Return a list of the live threads."
79 (with-all-threads-lock
80 (copy-list *all-threads*)))
82 (declaim (inline current-thread-sap))
83 (defun current-thread-sap ()
84 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
86 (declaim (inline current-thread-os-thread))
87 (defun current-thread-os-thread ()
89 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
91 (defun init-initial-thread ()
92 (/show0 "Entering INIT-INITIAL-THREAD")
93 (let ((initial-thread (%make-thread :name "initial thread"
95 :os-thread (current-thread-os-thread))))
96 (setq *current-thread* initial-thread)
97 ;; Either *all-threads* is empty or it contains exactly one thread
98 ;; in case we are in reinit since saving core with multiple
99 ;; threads doesn't work.
100 (setq *all-threads* (list initial-thread))))
106 ;; FIXME it would be good to define what a thread id is or isn't
107 ;; (our current assumption is that it's a fixnum). It so happens
108 ;; that on Linux it's a pid, but it might not be on posix thread
110 (define-alien-routine ("create_thread" %create-thread)
111 unsigned-long (lisp-fun-address unsigned-long))
113 (define-alien-routine "signal_interrupt_thread"
114 integer (os-thread unsigned-long))
116 (define-alien-routine "block_deferrable_signals"
121 (declaim (inline %lutex-init %lutex-wait %lutex-wake
122 %lutex-lock %lutex-unlock))
124 (define-alien-routine ("lutex_init" %lutex-init)
125 int (lutex unsigned-long))
127 (define-alien-routine ("lutex_wait" %lutex-wait)
128 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
130 (define-alien-routine ("lutex_wake" %lutex-wake)
131 int (lutex unsigned-long) (n int))
133 (define-alien-routine ("lutex_lock" %lutex-lock)
134 int (lutex unsigned-long))
136 (define-alien-routine ("lutex_trylock" %lutex-trylock)
137 int (lutex unsigned-long))
139 (define-alien-routine ("lutex_unlock" %lutex-unlock)
140 int (lutex unsigned-long))
142 (define-alien-routine ("lutex_destroy" %lutex-destroy)
143 int (lutex unsigned-long))
145 ;; FIXME: Defining a whole bunch of alien-type machinery just for
146 ;; passing primitive lutex objects directly to foreign functions
147 ;; doesn't seem like fun right now. So instead we just manually
148 ;; pin the lutex, get its address, and let the callee untag it.
149 (defmacro with-lutex-address ((name lutex) &body body)
150 `(let ((,name ,lutex))
151 (with-pinned-objects (,name)
152 (let ((,name (get-lisp-obj-address ,name)))
156 (/show0 "Entering MAKE-LUTEX")
157 ;; Suppress GC until the lutex has been properly registered with
160 (let ((lutex (sb!vm::%make-lutex)))
163 (with-lutex-address (lutex lutex)
169 (declaim (inline futex-wait %futex-wait futex-wake))
171 (define-alien-routine ("futex_wait" %futex-wait)
172 int (word unsigned-long) (old-value unsigned-long)
173 (to-sec long) (to-usec unsigned-long))
175 (defun futex-wait (word old to-sec to-usec)
177 (%futex-wait word old to-sec to-usec)))
179 (define-alien-routine "futex_wake"
180 int (word unsigned-long) (n unsigned-long))))
182 ;;; used by debug-int.lisp to access interrupt contexts
183 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
185 (defun sb!vm::current-thread-offset-sap (n)
186 (declare (type (unsigned-byte 27) n))
187 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
188 (* n sb!vm:n-word-bytes)))
191 (defun sb!vm::current-thread-offset-sap (n)
192 (declare (type (unsigned-byte 27) n))
193 (sb!vm::current-thread-offset-sap n))
195 (declaim (inline get-spinlock release-spinlock))
197 ;; Should always be called with interrupts disabled.
198 (defun get-spinlock (spinlock)
199 (declare (optimize (speed 3) (safety 0)))
200 (let* ((new *current-thread*)
201 (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
204 (error "Recursive lock attempt on ~S." spinlock))
207 (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
209 (return-from get-spinlock t))))
210 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
211 ;; If interrupts are enabled, but we are allowed to enabled them,
212 ;; check for pending interrupts every once in a while.
214 (loop repeat 128 do (cas)) ; 128 is arbitrary here
215 (sb!unix::%check-interrupts))
219 (defun release-spinlock (spinlock)
220 (declare (optimize (speed 3) (safety 0)))
221 ;; Simply setting SPINLOCK-VALUE to NIL is not enough as it does not
222 ;; propagate to other processors, plus without a memory barrier the
223 ;; CPU might reorder instructions allowing code from the critical
224 ;; section to leak out. Use COMPARE-AND-SWAP for the memory barrier
225 ;; effect and do some sanity checking while we are at it.
226 (unless (eq *current-thread*
227 (sb!ext:compare-and-swap (spinlock-value spinlock)
228 *current-thread* nil))
229 (error "Only the owner can release the spinlock ~S." spinlock)))
234 (setf (fdocumentation 'make-mutex 'function)
236 (fdocumentation 'mutex-name 'function)
237 "The name of the mutex. Setfable.")
239 #!+(and sb-thread (not sb-lutex))
241 (define-structure-slot-addressor mutex-state-address
244 ;; Important: current code assumes these are fixnums or other
245 ;; lisp objects that don't need pinning.
246 (defconstant +lock-free+ 0)
247 (defconstant +lock-taken+ 1)
248 (defconstant +lock-contested+ 2))
250 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
252 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
253 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
254 non-NIL and the mutex is in use, sleep until it is available.
256 Note: using GET-MUTEX to assign a MUTEX to another thread then the
257 current one is not recommended, and liable to be deprecated.
259 GET-MUTEX is not interrupt safe. The correct way to call it is:
263 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
266 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
267 call while the mutex is in an inconsistent state while
268 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
270 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
272 (declare (type mutex mutex) (optimize (speed 3))
273 #!-sb-thread (ignore waitp))
275 (setq new-owner *current-thread*))
276 (let ((old (mutex-%owner mutex)))
277 (when (eq new-owner old)
278 (error "Recursive lock attempt ~S." mutex))
281 (error "Strange deadlock on ~S in an unithreaded build?" mutex)
282 (setf (mutex-%owner mutex) new-owner)))
285 ;; FIXME: Lutexes do not currently support deadlines, as at least
286 ;; on Darwin pthread_foo_timedbar functions are not supported:
287 ;; this means that we probably need to use the Carbon multiprocessing
288 ;; functions on Darwin.
290 ;; FIXME: This is definitely not interrupt safe: what happens if
291 ;; we get hit (1) during the lutex calls (ok, they may be safe,
292 ;; but has that been checked?) (2) after the lutex call, but
293 ;; before setting the mutex owner.
295 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
297 (with-interrupts (%lutex-lock lutex))
298 (%lutex-trylock lutex))))
299 (setf (mutex-%owner mutex) new-owner)
302 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
305 (unless (or (eql +lock-free+ old) (not waitp))
308 (when (or (eql +lock-contested+ old)
309 (not (eql +lock-free+
310 (sb!ext:compare-and-swap (mutex-state mutex)
313 ;; Wait on the contested lock.
314 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
315 (when (= 1 (with-pinned-objects (mutex)
316 (futex-wait (mutex-state-address mutex)
317 (get-lisp-obj-address +lock-contested+)
321 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
325 (unless (eql +lock-free+ old)
327 (cond ((eql +lock-free+ old)
328 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
331 (bug "Old owner in free mutex: ~S" prev))
334 (bug "Failed to acquire lock with WAITP."))))))
336 (defun release-mutex (mutex)
338 "Release MUTEX by setting it to NIL. Wake up threads waiting for
341 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
344 Signals a WARNING is current thread is not the current owner of the
346 (declare (type mutex mutex))
347 ;; Order matters: set owner to NIL before releasing state.
348 (let* ((self *current-thread*)
349 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
350 (unless (eql self old-owner)
351 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
352 (setf (mutex-%owner mutex) nil)))
356 (with-lutex-address (lutex (mutex-lutex mutex))
357 (%lutex-unlock lutex))
359 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
360 +lock-taken+ +lock-free+)))
361 (when (eql old +lock-contested+)
362 (sb!ext:compare-and-swap (mutex-state mutex)
363 +lock-contested+ +lock-free+)
364 (with-pinned-objects (mutex)
365 (futex-wake (mutex-state-address mutex) 1))))
368 ;;;; waitqueues/condition variables
370 (defstruct (waitqueue (:constructor %make-waitqueue))
373 (name nil :type (or null simple-string))
374 #!+(and sb-lutex sb-thread)
379 (defun make-waitqueue (&key name)
381 "Create a waitqueue."
382 (%make-waitqueue :name name))
385 (setf (fdocumentation 'waitqueue-name 'function)
386 "The name of the waitqueue. Setfable.")
388 #!+(and sb-thread (not sb-lutex))
389 (define-structure-slot-addressor waitqueue-data-address
393 (defun condition-wait (queue mutex)
395 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
396 thread may subsequently notify us using CONDITION-NOTIFY, at which
397 time we reacquire MUTEX and return to the caller."
398 #!-sb-thread (declare (ignore queue))
400 #!-sb-thread (error "Not supported in unithread builds.")
402 (let ((me *current-thread*))
403 (assert (eq me (mutex-%owner mutex)))
404 (/show0 "CONDITION-WAITing")
406 ;; Need to disable interrupts so that we don't miss setting the owner on
407 ;; our way out. (pthread_cond_wait handles the actual re-acquisition.)
411 (setf (mutex-%owner mutex) nil)
412 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
413 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
414 (with-local-interrupts
415 (%lutex-wait queue-lutex-address mutex-lutex-address)))))
416 (setf (mutex-%owner mutex) me)))
418 ;; Need to disable interrupts so that we don't miss grabbing the mutex
422 (let ((me *current-thread*))
423 ;; FIXME: should we do something to ensure that the result
424 ;; of this setf is visible to all CPUs?
425 (setf (waitqueue-data queue) me)
426 (release-mutex mutex)
427 ;; Now we go to sleep using futex-wait. If anyone else
428 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
429 ;; this comment, it will change queue->data, and so
430 ;; futex-wait returns immediately instead of sleeping.
431 ;; Ergo, no lost wakeup. We may get spurious wakeups,
433 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
434 (when (= 1 (with-pinned-objects (queue me)
435 (allow-with-interrupts
436 (futex-wait (waitqueue-data-address queue)
437 (get-lisp-obj-address me)
438 (or to-sec -1) ;; our way if saying "no timeout"
441 ;; If we are interrupted while waiting, we should do these things
442 ;; before returning. Ideally, in the case of an unhandled signal,
443 ;; we should do them before entering the debugger, but this is
444 ;; better than nothing.
445 (get-mutex mutex)))))
447 (defun condition-notify (queue &optional (n 1))
449 "Notify N threads waiting on QUEUE."
450 #!-sb-thread (declare (ignore queue n))
451 #!-sb-thread (error "Not supported in unithread builds.")
453 (declare (type (and fixnum (integer 1)) n))
454 (/show0 "Entering CONDITION-NOTIFY")
458 (with-lutex-address (lutex (waitqueue-lutex queue))
459 (%lutex-wake lutex n))
460 ;; no problem if >1 thread notifies during the comment in
461 ;; condition-wait: as long as the value in queue-data isn't the
462 ;; waiting thread's id, it matters not what it is
463 ;; XXX we should do something to ensure that the result of this setf
464 ;; is visible to all CPUs
466 (let ((me *current-thread*))
468 (setf (waitqueue-data queue) me)
469 (with-pinned-objects (queue)
470 (futex-wake (waitqueue-data-address queue) n))))))
472 (defun condition-broadcast (queue)
474 "Notify all threads waiting on QUEUE."
475 (condition-notify queue
476 ;; On a 64-bit platform truncating M-P-F to an int results
477 ;; in -1, which wakes up only one thread.
479 most-positive-fixnum)))
483 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
485 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
486 should be considered an implementation detail, and may change in the
488 (name nil :type (or null simple-string))
489 (%count 0 :type (integer 0))
490 (waitcount 0 :type (integer 0))
492 (queue (make-waitqueue)))
494 (setf (fdocumentation 'semaphore-name 'function)
495 "The name of the semaphore INSTANCE. Setfable.")
497 (declaim (inline semaphore-count))
498 (defun semaphore-count (instance)
499 "Returns the current count of the semaphore INSTANCE."
500 (semaphore-%count instance))
502 (defun make-semaphore (&key name (count 0))
504 "Create a semaphore with the supplied COUNT and NAME."
505 (%make-semaphore name count))
507 (defun wait-on-semaphore (semaphore)
509 "Decrement the count of SEMAPHORE if the count would not be
510 negative. Else blocks until the semaphore can be decremented."
511 ;; A more direct implementation based directly on futexes should be
514 ;; We need to disable interrupts so that we don't forget to decrement the
515 ;; waitcount (which would happen if an asynch interrupt should catch us on
516 ;; our way out from the loop.)
517 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
518 ;; Quick check: is it positive? If not, enter the wait loop.
519 (let ((count (semaphore-%count semaphore)))
521 (setf (semaphore-%count semaphore) (1- count))
524 (incf (semaphore-waitcount semaphore))
525 (loop until (plusp (setf count (semaphore-%count semaphore)))
526 do (condition-wait (semaphore-queue semaphore) (semaphore-mutex semaphore)))
527 (setf (semaphore-%count semaphore) (1- count)))
528 (decf (semaphore-waitcount semaphore)))))))
530 (defun signal-semaphore (semaphore &optional (n 1))
532 "Increment the count of SEMAPHORE by N. If there are threads waiting
533 on this semaphore, then N of them is woken up."
534 (declare (type (integer 1) n))
535 ;; Need to disable interrupts so that we don't lose a wakeup after we have
536 ;; incremented the count.
537 (with-system-mutex ((semaphore-mutex semaphore))
538 (let ((waitcount (semaphore-waitcount semaphore))
539 (count (incf (semaphore-%count semaphore) n)))
540 (when (plusp waitcount)
541 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
543 ;;;; job control, independent listeners
546 (lock (make-mutex :name "session lock"))
548 (interactive-threads nil)
549 (interactive-threads-queue (make-waitqueue)))
551 (defvar *session* nil)
553 ;;; The debugger itself tries to acquire the session lock, don't let
554 ;;; funny situations (like getting a sigint while holding the session
555 ;;; lock) occur. At the same time we need to allow interrupts while
556 ;;; *waiting* for the session lock for things like GET-FOREGROUND
557 ;;; to be interruptible.
559 ;;; Take care: we sometimes need to obtain the session lock while holding
560 ;;; on to *ALL-THREADS-LOCK*, so we must _never_ obtain it _after_ getting
561 ;;; a session lock! (Deadlock risk.)
563 ;;; FIXME: It would be good to have ordered locks to ensure invariants like
565 (defmacro with-session-lock ((session) &body body)
566 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
569 (defun new-session ()
570 (make-session :threads (list *current-thread*)
571 :interactive-threads (list *current-thread*)))
573 (defun init-job-control ()
574 (/show0 "Entering INIT-JOB-CONTROL")
575 (setf *session* (new-session))
576 (/show0 "Exiting INIT-JOB-CONTROL"))
578 (defun %delete-thread-from-session (thread session)
579 (with-session-lock (session)
580 (setf (session-threads session)
581 (delete thread (session-threads session))
582 (session-interactive-threads session)
583 (delete thread (session-interactive-threads session)))))
585 (defun call-with-new-session (fn)
586 (%delete-thread-from-session *current-thread* *session*)
587 (let ((*session* (new-session)))
590 (defmacro with-new-session (args &body forms)
591 (declare (ignore args)) ;for extensibility
592 (sb!int:with-unique-names (fb-name)
593 `(labels ((,fb-name () ,@forms))
594 (call-with-new-session (function ,fb-name)))))
596 ;;; Remove thread from its session, if it has one.
598 (defun handle-thread-exit (thread)
599 (/show0 "HANDLING THREAD EXIT")
600 ;; We're going down, can't handle interrupts sanely anymore.
601 ;; GC remains enabled.
602 (block-deferrable-signals)
604 (with-all-threads-lock
605 (setf (thread-%alive-p thread) nil)
606 (setf (thread-os-thread thread) nil)
607 (setq *all-threads* (delete thread *all-threads*))
609 (%delete-thread-from-session thread *session*)))
612 (/show0 "FREEING MUTEX LUTEX")
613 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
614 (%lutex-destroy lutex))))
616 (defun terminate-session ()
618 "Kill all threads in session except for this one. Does nothing if current
619 thread is not the foreground thread."
620 ;; FIXME: threads created in other threads may escape termination
622 (with-session-lock (*session*)
623 (and (eq *current-thread*
624 (car (session-interactive-threads *session*)))
625 (session-threads *session*)))))
626 ;; do the kill after dropping the mutex; unwind forms in dying
627 ;; threads may want to do session things
628 (dolist (thread to-kill)
629 (unless (eq thread *current-thread*)
630 ;; terminate the thread but don't be surprised if it has
631 ;; exited in the meantime
632 (handler-case (terminate-thread thread)
633 (interrupt-thread-error ()))))))
635 ;;; called from top of invoke-debugger
636 (defun debugger-wait-until-foreground-thread (stream)
637 "Returns T if thread had been running in background, NIL if it was
639 (declare (ignore stream))
643 (with-session-lock (*session*)
644 (not (member *current-thread*
645 (session-interactive-threads *session*))))
648 (defun get-foreground ()
651 (let ((was-foreground t))
653 (/show0 "Looping in GET-FOREGROUND")
654 (with-session-lock (*session*)
655 (let ((int-t (session-interactive-threads *session*)))
656 (when (eq (car int-t) *current-thread*)
657 (unless was-foreground
658 (format *query-io* "Resuming thread ~A~%" *current-thread*))
659 (return-from get-foreground t))
660 (setf was-foreground nil)
661 (unless (member *current-thread* int-t)
662 (setf (cdr (last int-t))
663 (list *current-thread*)))
665 (session-interactive-threads-queue *session*)
666 (session-lock *session*)))))))
668 (defun release-foreground (&optional next)
670 "Background this thread. If NEXT is supplied, arrange for it to
671 have the foreground next."
672 #!-sb-thread (declare (ignore next))
675 (with-session-lock (*session*)
676 (when (rest (session-interactive-threads *session*))
677 (setf (session-interactive-threads *session*)
678 (delete *current-thread* (session-interactive-threads *session*))))
680 (setf (session-interactive-threads *session*)
682 (delete next (session-interactive-threads *session*)))))
683 (condition-broadcast (session-interactive-threads-queue *session*))))
685 (defun foreground-thread ()
686 (car (session-interactive-threads *session*)))
688 (defun make-listener-thread (tty-name)
689 (assert (probe-file tty-name))
690 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
691 (out (sb!unix:unix-dup in))
692 (err (sb!unix:unix-dup in)))
693 (labels ((thread-repl ()
694 (sb!unix::unix-setsid)
695 (let* ((sb!impl::*stdin*
696 (make-fd-stream in :input t :buffering :line
699 (make-fd-stream out :output t :buffering :line
702 (make-fd-stream err :output t :buffering :line
705 (make-fd-stream err :input t :output t
708 (sb!impl::*descriptor-handlers* nil))
711 (sb!impl::toplevel-repl nil)
712 (sb!int:flush-standard-output-streams))))))
713 (make-thread #'thread-repl))))
717 (defun make-thread (function &key name)
719 "Create a new thread of NAME that runs FUNCTION. When the function
720 returns the thread exits. The return values of FUNCTION are kept
721 around and can be retrieved by JOIN-THREAD."
722 #!-sb-thread (declare (ignore function name))
723 #!-sb-thread (error "Not supported in unithread builds.")
725 (let* ((thread (%make-thread :name name))
726 (setup-sem (make-semaphore :name "Thread setup semaphore"))
727 (real-function (coerce function 'function))
730 ;; In time we'll move some of the binding presently done in C
733 ;; KLUDGE: Here we have a magic list of variables that are
734 ;; not thread-safe for one reason or another. As people
735 ;; report problems with the thread safety of certain
736 ;; variables, (e.g. "*print-case* in multiple threads
737 ;; broken", sbcl-devel 2006-07-14), we add a few more
738 ;; bindings here. The Right Thing is probably some variant
739 ;; of Allegro's *cl-default-special-bindings*, as that is at
740 ;; least accessible to users to secure their own libraries.
742 (let* ((*current-thread* thread)
743 (*restart-clusters* nil)
744 (*handler-clusters* (sb!kernel::initial-handler-clusters))
745 (*condition-restarts* nil)
746 (sb!impl::*deadline* nil)
747 (sb!impl::*step-out* nil)
748 ;; internal printer variables
749 (sb!impl::*previous-case* nil)
750 (sb!impl::*previous-readtable-case* nil)
752 (sb!impl::*merge-sort-temp-vector* empty)
753 (sb!impl::*zap-array-data-temp* empty)
754 (sb!impl::*internal-symbol-output-fun* nil)
755 (sb!impl::*descriptor-handlers* nil)) ; serve-event
757 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
758 (setf (thread-os-thread thread) (current-thread-os-thread))
759 (with-mutex ((thread-result-lock thread))
760 (with-all-threads-lock
761 (push thread *all-threads*))
762 (with-session-lock (*session*)
763 (push thread (session-threads *session*)))
764 (setf (thread-%alive-p thread) t)
765 (signal-semaphore setup-sem)
766 ;; can't use handling-end-of-the-world, because that flushes
767 ;; output streams, and we don't necessarily have any (or we
768 ;; could be sharing them)
769 (catch 'sb!impl::toplevel-catcher
770 (catch 'sb!impl::%end-of-the-world
774 "~~@<Terminate this thread (~A)~~@:>"
778 ;; now that most things have a chance to
779 ;; work properly without messing up other
780 ;; threads, it's time to enable signals
781 (sb!unix::reset-signal-mask)
782 (setf (thread-result thread)
785 (funcall real-function)))))
786 (handle-thread-exit thread)))))))
788 ;; Keep INITIAL-FUNCTION pinned until the child thread is
789 ;; initialized properly.
790 (with-pinned-objects (initial-function)
793 (get-lisp-obj-address initial-function))))
794 (when (zerop os-thread)
795 (error "Can't create a new thread"))
796 (wait-on-semaphore setup-sem)
799 (define-condition join-thread-error (error)
800 ((thread :reader join-thread-error-thread :initarg :thread))
802 (:documentation "Joining thread failed.")
803 (:report (lambda (c s)
804 (format s "Joining thread failed: thread ~A ~
805 has not returned normally."
806 (join-thread-error-thread c)))))
809 (setf (fdocumentation 'join-thread-error-thread 'function)
810 "The thread that we failed to join.")
812 (defun join-thread (thread &key (default nil defaultp))
814 "Suspend current thread until THREAD exits. Returns the result
815 values of the thread function. If the thread does not exit normally,
816 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
817 (with-mutex ((thread-result-lock thread))
818 (cond ((car (thread-result thread))
819 (values-list (cdr (thread-result thread))))
823 (error 'join-thread-error :thread thread)))))
825 (defun destroy-thread (thread)
827 "Deprecated. Same as TERMINATE-THREAD."
828 (terminate-thread thread))
830 (define-condition interrupt-thread-error (error)
831 ((thread :reader interrupt-thread-error-thread :initarg :thread))
833 (:documentation "Interrupting thread failed.")
834 (:report (lambda (c s)
835 (format s "Interrupt thread failed: thread ~A has exited."
836 (interrupt-thread-error-thread c)))))
839 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
840 "The thread that was not interrupted.")
842 (defmacro with-interruptions-lock ((thread) &body body)
843 `(with-system-mutex ((thread-interruptions-lock ,thread))
846 ;; Called from the signal handler in C.
847 (defun run-interruption ()
850 (let ((interruption (with-interruptions-lock (*current-thread*)
851 (pop (thread-interruptions *current-thread*)))))
854 (funcall interruption))
857 ;; The order of interrupt execution is peculiar. If thread A
858 ;; interrupts thread B with I1, I2 and B for some reason receives I1
859 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
860 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
861 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
862 ;; just one scenario, and the order of thread interrupt execution is
864 (defun interrupt-thread (thread function)
866 "Interrupt the live THREAD and make it run FUNCTION. A moderate
867 degree of care is expected for use of INTERRUPT-THREAD, due to its
868 nature: if you interrupt a thread that was holding important locks
869 then do something that turns out to need those locks, you probably
870 won't like the effect."
871 #!-sb-thread (declare (ignore thread))
873 (with-interrupt-bindings
874 (with-interrupts (funcall function)))
876 (if (eq thread *current-thread*)
877 (with-interrupt-bindings
878 (with-interrupts (funcall function)))
879 (let ((os-thread (thread-os-thread thread)))
880 (cond ((not os-thread)
881 (error 'interrupt-thread-error :thread thread))
883 (with-interruptions-lock (thread)
884 (push function (thread-interruptions thread)))
885 (when (minusp (signal-interrupt-thread os-thread))
886 (error 'interrupt-thread-error :thread thread)))))))
888 (defun terminate-thread (thread)
890 "Terminate the thread identified by THREAD, by causing it to run
891 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
892 (interrupt-thread thread 'sb!ext:quit))
894 (define-alien-routine "thread_yield" int)
897 (setf (fdocumentation 'thread-yield 'function)
898 "Yield the processor to other threads.")
900 ;;; internal use only. If you think you need to use these, either you
901 ;;; are an SBCL developer, are doing something that you should discuss
902 ;;; with an SBCL developer first, or are doing something that you
903 ;;; should probably discuss with a professional psychiatrist first
906 (defun %thread-sap (thread)
907 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
908 (target (thread-os-thread thread)))
910 (when (sap= thread-sap (int-sap 0)) (return nil))
911 (let ((os-thread (sap-ref-word thread-sap
912 (* sb!vm:n-word-bytes
913 sb!vm::thread-os-thread-slot))))
914 (when (= os-thread target) (return thread-sap))
916 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
917 sb!vm::thread-next-slot)))))))
919 (defun %symbol-value-in-thread (symbol thread)
921 ;; Prevent the dead from dying completely while we look for the TLS area...
922 (with-all-threads-lock
923 (if (thread-alive-p thread)
924 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
925 (tl-val (sap-ref-word (%thread-sap thread) offset)))
926 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
928 (return-from %symbol-value-in-thread (values (make-lisp-obj tl-val) t))))
929 (return-from %symbol-value-in-thread (values nil nil))))
931 (error "Cannot read thread-local symbol value: ~S unbound in ~S" symbol thread)))
933 (defun %set-symbol-value-in-thread (symbol thread value)
935 (with-pinned-objects (value)
936 ;; Prevent the dead from dying completely while we look for the TLS area...
937 (with-all-threads-lock
938 (if (thread-alive-p thread)
939 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
940 (sap (%thread-sap thread))
941 (tl-val (sap-ref-word sap offset)))
942 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
944 (setf (sap-ref-word sap offset) (get-lisp-obj-address value)))
945 (return-from %set-symbol-value-in-thread (values value t)))
946 (return-from %set-symbol-value-in-thread (values nil nil)))))
948 (error "Cannot set thread-local symbol value: ~S unbound in ~S" symbol thread))))
950 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
951 (sb!vm::locked-symbol-global-value-add symbol-name delta))
955 (defun thread-stepping ()
957 (sap-ref-word (current-thread-sap)
958 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
960 (defun (setf thread-stepping) (value)
961 (setf (sap-ref-word (current-thread-sap)
962 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
963 (get-lisp-obj-address value)))