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")
16 (define-condition thread-error (error)
17 ((thread :reader thread-error-thread :initarg :thread))
20 "Conditions of type THREAD-ERROR are signalled when thread operations fail.
21 The offending thread is initialized by the :THREAD initialization argument and
22 read by the function THREAD-ERROR-THREAD."))
26 (fdocumentation 'thread-error-thread 'function)
27 "Return the offending thread that the THREAD-ERROR pertains to.")
29 (define-condition symbol-value-in-thread-error (cell-error thread-error)
30 ((info :reader symbol-value-in-thread-error-info :initarg :info))
32 (lambda (condition stream)
33 (destructuring-bind (op problem)
34 (symbol-value-in-thread-error-info condition)
35 (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
37 (cell-error-name condition)
38 (thread-error-thread condition)
40 (:unbound-in-thread "the symbol is unbound in thread.")
41 (:no-tls-value "the symbol has no thread-local value.")
42 (:thread-dead "the thread has exited.")
43 (:invalid-tls-value "the thread-local value is not valid."))))))
46 "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
47 the symbol not having a thread-local value, or the target thread having
48 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
49 offending thread using THREAD-ERROR-THREAD."))
51 (define-condition join-thread-error (thread-error) ()
52 (:report (lambda (c s)
53 (format s "Joining thread failed: thread ~A ~
54 did not return normally."
55 (thread-error-thread c))))
58 "Signalled when joining a thread fails due to abnormal exit of the thread
59 to be joined. The offending thread can be accessed using
60 THREAD-ERROR-THREAD."))
62 (defun join-thread-error-thread (condition)
63 (thread-error-thread condition))
64 (define-compiler-macro join-thread-error-thread (condition)
65 (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
66 `(thread-error-thread ,condition))
70 (fdocumentation 'join-thread-error-thread 'function)
71 "The thread that we failed to join. Deprecated, use THREAD-ERROR-THREAD
74 (define-condition interrupt-thread-error (thread-error) ()
75 (:report (lambda (c s)
76 (format s "Interrupt thread failed: thread ~A has exited."
77 (thread-error-thread c))))
80 "Signalled when interrupting a thread fails because the thread has already
81 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
83 (defun interrupt-thread-error-thread (condition)
84 (thread-error-thread condition))
85 (define-compiler-macro interrupt-thread-error-thread (condition)
86 (deprecation-warning 'join-thread-error-thread 'thread-error-thread)
87 `(thread-error-thread ,condition))
91 (fdocumentation 'interrupt-thread-error-thread 'function)
92 "The thread that was not interrupted. Deprecated, use THREAD-ERROR-THREAD
95 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
96 ;;; necessary because threads are only supported with the conservative
97 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
98 ;;; are treated as references.
100 ;;; set the doc here because in early-thread FDOCUMENTATION is not
103 (setf (fdocumentation '*current-thread* 'variable)
104 "Bound in each thread to the thread itself.")
108 (fdocumentation 'thread-name 'function)
109 "Name of the thread. Can be assigned to using SETF. Thread names can be
110 arbitrary printable objects, and need not be unique.")
112 (def!method print-object ((thread thread) stream)
113 (print-unreadable-object (thread stream :type t :identity t)
114 (let* ((cookie (list thread))
115 (info (if (thread-alive-p thread)
118 (join-thread thread :default cookie))))
119 (state (if (eq :running info)
121 (if (eq cookie (car info))
124 (values (when (eq :finished state) info)))
126 "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
132 (defun thread-alive-p (thread)
134 "Return T if THREAD is still alive. Note that the return value is
135 potentially stale even before the function returns, as the thread may exit at
137 (thread-%alive-p thread))
139 ;; A thread is eligible for gc iff it has finished and there are no
140 ;; more references to it. This list is supposed to keep a reference to
141 ;; all running threads.
142 (defvar *all-threads* ())
143 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
145 (defvar *default-alloc-signal* nil)
147 (defmacro with-all-threads-lock (&body body)
148 `(with-system-mutex (*all-threads-lock*)
151 (defun list-all-threads ()
153 "Return a list of the live threads. Note that the return value is
154 potentially stale even before the function returns, as new threads may be
155 created and old ones may exit at any time."
156 (with-all-threads-lock
157 (copy-list *all-threads*)))
159 (declaim (inline current-thread-sap))
160 (defun current-thread-sap ()
161 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
163 (declaim (inline current-thread-os-thread))
164 (defun current-thread-os-thread ()
166 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
170 (defun init-initial-thread ()
171 (/show0 "Entering INIT-INITIAL-THREAD")
172 (let ((initial-thread (%make-thread :name "initial thread"
174 :os-thread (current-thread-os-thread))))
175 (setq *current-thread* initial-thread)
176 ;; Either *all-threads* is empty or it contains exactly one thread
177 ;; in case we are in reinit since saving core with multiple
178 ;; threads doesn't work.
179 (setq *all-threads* (list initial-thread))))
182 ;;;; Aliens, low level stuff
184 (define-alien-routine "kill_safely"
186 (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
191 ;; FIXME it would be good to define what a thread id is or isn't
192 ;; (our current assumption is that it's a fixnum). It so happens
193 ;; that on Linux it's a pid, but it might not be on posix thread
195 (define-alien-routine ("create_thread" %create-thread)
196 unsigned-long (lisp-fun-address unsigned-long))
198 (declaim (inline %block-deferrable-signals))
199 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
201 (where sb!alien:unsigned-long)
202 (old sb!alien:unsigned-long))
204 (defun block-deferrable-signals ()
205 (%block-deferrable-signals 0 0))
209 (declaim (inline %lutex-init %lutex-wait %lutex-wake
210 %lutex-lock %lutex-unlock))
212 (define-alien-routine ("lutex_init" %lutex-init)
213 int (lutex unsigned-long))
215 (define-alien-routine ("lutex_wait" %lutex-wait)
216 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
218 (define-alien-routine ("lutex_wake" %lutex-wake)
219 int (lutex unsigned-long) (n int))
221 (define-alien-routine ("lutex_lock" %lutex-lock)
222 int (lutex unsigned-long))
224 (define-alien-routine ("lutex_trylock" %lutex-trylock)
225 int (lutex unsigned-long))
227 (define-alien-routine ("lutex_unlock" %lutex-unlock)
228 int (lutex unsigned-long))
230 (define-alien-routine ("lutex_destroy" %lutex-destroy)
231 int (lutex unsigned-long))
233 ;; FIXME: Defining a whole bunch of alien-type machinery just for
234 ;; passing primitive lutex objects directly to foreign functions
235 ;; doesn't seem like fun right now. So instead we just manually
236 ;; pin the lutex, get its address, and let the callee untag it.
237 (defmacro with-lutex-address ((name lutex) &body body)
238 `(let ((,name ,lutex))
239 (with-pinned-objects (,name)
240 (let ((,name (get-lisp-obj-address ,name)))
244 (/show0 "Entering MAKE-LUTEX")
245 ;; Suppress GC until the lutex has been properly registered with
248 (let ((lutex (sb!vm::%make-lutex)))
251 (with-lutex-address (lutex lutex)
257 (declaim (inline futex-wait %futex-wait futex-wake))
259 (define-alien-routine ("futex_wait" %futex-wait)
260 int (word unsigned-long) (old-value unsigned-long)
261 (to-sec long) (to-usec unsigned-long))
263 (defun futex-wait (word old to-sec to-usec)
265 (%futex-wait word old to-sec to-usec)))
267 (define-alien-routine "futex_wake"
268 int (word unsigned-long) (n unsigned-long))))
270 ;;; used by debug-int.lisp to access interrupt contexts
271 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
273 (defun sb!vm::current-thread-offset-sap (n)
274 (declare (type (unsigned-byte 27) n))
275 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
276 (* n sb!vm:n-word-bytes)))
279 (defun sb!vm::current-thread-offset-sap (n)
280 (declare (type (unsigned-byte 27) n))
281 (sb!vm::current-thread-offset-sap n))
286 (declaim (inline get-spinlock release-spinlock))
288 ;;; Should always be called with interrupts disabled.
289 (defun get-spinlock (spinlock)
290 (declare (optimize (speed 3) (safety 0)))
291 (let* ((new *current-thread*)
292 (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
295 (error "Recursive lock attempt on ~S." spinlock))
298 (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
300 (return-from get-spinlock t))))
301 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
302 ;; If interrupts are disabled, but we are allowed to
303 ;; enabled them, check for pending interrupts every once
304 ;; in a while. %CHECK-INTERRUPTS is taking shortcuts, make
305 ;; sure that deferrables are unblocked by doing an empty
306 ;; WITH-INTERRUPTS once.
310 (loop repeat 128 do (cas)) ; 128 is arbitrary here
311 (sb!unix::%check-interrupts)))
315 (defun release-spinlock (spinlock)
316 (declare (optimize (speed 3) (safety 0)))
317 ;; On x86 and x86-64 we can get away with no memory barriers, (see
318 ;; Linux kernel mailing list "spin_unlock optimization(i386)"
319 ;; thread, summary at
320 ;; http://kt.iserv.nl/kernel-traffic/kt19991220_47.html#1.
322 ;; If the compiler may reorder this with other instructions, insert
323 ;; compiler barrier here.
325 ;; FIXME: this does not work on SMP Pentium Pro and OOSTORE systems,
326 ;; neither on most non-x86 architectures (but we don't have threads
328 (setf (spinlock-value spinlock) nil)
330 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
332 #!+(not (or x86 x86-64))
339 (setf (fdocumentation 'make-mutex 'function)
341 (fdocumentation 'mutex-name 'function)
342 "The name of the mutex. Setfable.")
344 #!+(and sb-thread (not sb-lutex))
346 (define-structure-slot-addressor mutex-state-address
349 ;; Important: current code assumes these are fixnums or other
350 ;; lisp objects that don't need pinning.
351 (defconstant +lock-free+ 0)
352 (defconstant +lock-taken+ 1)
353 (defconstant +lock-contested+ 2))
355 (defun mutex-owner (mutex)
356 "Current owner of the mutex, NIL if the mutex is free. Naturally,
357 this is racy by design (another thread may acquire the mutex after
358 this function returns), it is intended for informative purposes. For
359 testing whether the current thread is holding a mutex see
361 ;; Make sure to get the current value.
362 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
364 (defun get-mutex (mutex &optional (new-owner *current-thread*)
365 (waitp t) (timeout nil))
367 "Deprecated in favor of GRAB-MUTEX."
368 (declare (type mutex mutex) (optimize (speed 3))
369 #!-sb-thread (ignore waitp timeout))
371 (setq new-owner *current-thread*))
373 (let ((old (mutex-%owner mutex)))
374 (when (eq new-owner old)
375 (error "Recursive lock attempt ~S." mutex))
378 (error "Strange deadlock on ~S in an unithreaded build?" mutex)))
380 (setf (mutex-%owner mutex) new-owner)
383 ;; FIXME: Lutexes do not currently support deadlines, as at least
384 ;; on Darwin pthread_foo_timedbar functions are not supported:
385 ;; this means that we probably need to use the Carbon multiprocessing
386 ;; functions on Darwin.
388 ;; FIXME: This is definitely not interrupt safe: what happens if
389 ;; we get hit (1) during the lutex calls (ok, they may be safe,
390 ;; but has that been checked?) (2) after the lutex call, but
391 ;; before setting the mutex owner.
395 (error "Mutex timeouts not supported on this platform."))
396 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
398 (with-interrupts (%lutex-lock lutex))
399 (%lutex-trylock lutex))))
400 (setf (mutex-%owner mutex) new-owner)
404 ;; This is a direct translation of the Mutex 2 algorithm from
405 ;; "Futexes are Tricky" by Ulrich Drepper.
406 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
409 (unless (or (eql +lock-free+ old) (not waitp))
412 (when (or (eql +lock-contested+ old)
413 (not (eql +lock-free+
414 (sb!ext:compare-and-swap (mutex-state mutex)
417 ;; Wait on the contested lock.
419 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
420 (decode-timeout timeout)
421 (declare (ignore stop-sec stop-usec))
422 (case (with-pinned-objects (mutex)
423 (futex-wait (mutex-state-address mutex)
424 (get-lisp-obj-address +lock-contested+)
429 (return-from get-mutex nil)))
431 (otherwise (return))))))
432 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
436 (unless (eql +lock-free+ old)
438 (cond ((eql +lock-free+ old)
439 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
442 (bug "Old owner in free mutex: ~S" prev))
445 (bug "Failed to acquire lock with WAITP."))))))
447 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
449 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
450 the mutex is not immediately available, sleep until it is available.
452 If TIMEOUT is given, it specifies a relative timeout, in seconds, on
453 how long GRAB-MUTEX should try to acquire the lock in the contested
454 case. Unsupported on :SB-LUTEX platforms (eg. Darwin), where a non-NIL
455 TIMEOUT signals an error.
457 If GRAB-MUTEX returns T, the lock acquisition was successful. In case
458 of WAITP being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return
459 NIL which denotes that GRAB-MUTEX did -not- acquire the lock.
463 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
467 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
470 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding
471 the call while the mutex is in an inconsistent state while
472 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from
475 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
476 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
477 DEADLINE-TIMEOUT if the global deadline was due already on
480 The exact interplay of GRAB-MUTEX and deadlines are reserved to
481 change in future versions.
483 - It is recommended that you use WITH-MUTEX instead of calling
486 (get-mutex mutex nil waitp timeout))
488 (defun release-mutex (mutex &key (if-not-owner :punt))
490 "Release MUTEX by setting it to NIL. Wake up threads waiting for
493 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
496 If the current thread is not the owner of the mutex then it silently
497 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
498 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
499 IF-NOT-OWNER is :FORCE)."
500 (declare (type mutex mutex))
501 ;; Order matters: set owner to NIL before releasing state.
502 (let* ((self *current-thread*)
503 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
504 (unless (eql self old-owner)
506 ((:punt) (return-from release-mutex nil))
508 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
512 (setf (mutex-%owner mutex) nil)
514 (with-lutex-address (lutex (mutex-lutex mutex))
515 (%lutex-unlock lutex))
517 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
518 ;; unsigned-byte type this can be used:
520 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
521 ;; (unless (eql old +lock-free+)
522 ;; (setf (mutex-state mutex) +lock-free+)
523 ;; (with-pinned-objects (mutex)
524 ;; (futex-wake (mutex-state-address mutex) 1))))
525 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
526 +lock-taken+ +lock-free+)))
527 (when (eql old +lock-contested+)
528 (sb!ext:compare-and-swap (mutex-state mutex)
529 +lock-contested+ +lock-free+)
530 (with-pinned-objects (mutex)
531 (futex-wake (mutex-state-address mutex) 1))))
535 ;;;; Waitqueues/condition variables
537 (defstruct (waitqueue (:constructor %make-waitqueue))
540 (name nil :type (or null thread-name))
541 #!+(and sb-lutex sb-thread)
546 (defun make-waitqueue (&key name)
548 "Create a waitqueue."
549 (%make-waitqueue :name name))
552 (setf (fdocumentation 'waitqueue-name 'function)
553 "The name of the waitqueue. Setfable.")
555 #!+(and sb-thread (not sb-lutex))
556 (define-structure-slot-addressor waitqueue-token-address
560 (defun condition-wait (queue mutex)
562 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
563 thread may subsequently notify us using CONDITION-NOTIFY, at which
564 time we reacquire MUTEX and return to the caller.
566 Note that if CONDITION-WAIT unwinds (due to eg. a timeout) instead of
567 returning normally, it may do so without holding the mutex."
568 #!-sb-thread (declare (ignore queue))
570 #!-sb-thread (error "Not supported in unithread builds.")
572 (let ((me *current-thread*))
574 (assert (eq me (mutex-%owner mutex)))
575 (/show0 "CONDITION-WAITing")
577 ;; Need to disable interrupts so that we don't miss setting the
578 ;; owner on our way out. (pthread_cond_wait handles the actual
583 (setf (mutex-%owner mutex) nil)
584 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
585 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
586 (with-local-interrupts
587 (%lutex-wait queue-lutex-address mutex-lutex-address)))))
589 (setf (mutex-%owner mutex) me))))
591 ;; Need to disable interrupts so that we don't miss grabbing the
592 ;; mutex on our way out.
594 ;; This setf becomes visible to other CPUS due to the usual
595 ;; memory barrier semantics of lock acquire/release. This must
596 ;; not be moved into the loop else wakeups may be lost upon
597 ;; continuing after a deadline or EINTR.
598 (setf (waitqueue-token queue) me)
600 (multiple-value-bind (to-sec to-usec)
601 (allow-with-interrupts (decode-timeout nil))
602 (case (unwind-protect
603 (with-pinned-objects (queue me)
604 ;; RELEASE-MUTEX is purposefully as close to
605 ;; FUTEX-WAIT as possible to reduce the size of
606 ;; the window where the token may be set by a
608 (release-mutex mutex)
609 ;; Now we go to sleep using futex-wait. If
610 ;; anyone else manages to grab MUTEX and call
611 ;; CONDITION-NOTIFY during this comment, it
612 ;; will change the token, and so futex-wait
613 ;; returns immediately instead of sleeping.
614 ;; Ergo, no lost wakeup. We may get spurious
615 ;; wakeups, but that's ok.
616 (allow-with-interrupts
617 (futex-wait (waitqueue-token-address queue)
618 (get-lisp-obj-address me)
619 ;; our way of saying "no
623 ;; If we are interrupted while waiting, we should
624 ;; do these things before returning. Ideally, in
625 ;; the case of an unhandled signal, we should do
626 ;; them before entering the debugger, but this is
627 ;; better than nothing.
628 (allow-with-interrupts (get-mutex mutex)))
629 ;; ETIMEDOUT; we know it was a timeout, yet we cannot
630 ;; signal a deadline unconditionally here because the
631 ;; call to GET-MUTEX may already have signaled it.
633 ;; EINTR; we do not need to return to the caller because
634 ;; an interleaved wakeup would change the token causing an
635 ;; EWOULDBLOCK in the next iteration.
637 ;; EWOULDBLOCK, -1 here, is the possible spurious wakeup
638 ;; case. 0 is the normal wakeup.
639 (otherwise (return))))))))
641 (defun condition-notify (queue &optional (n 1))
643 "Notify N threads waiting on QUEUE. The same mutex that is used in
644 the corresponding CONDITION-WAIT must be held by this thread during
646 #!-sb-thread (declare (ignore queue n))
647 #!-sb-thread (error "Not supported in unithread builds.")
649 (declare (type (and fixnum (integer 1)) n))
650 (/show0 "Entering CONDITION-NOTIFY")
654 (with-lutex-address (lutex (waitqueue-lutex queue))
655 (%lutex-wake lutex n))
656 ;; No problem if >1 thread notifies during the comment in condition-wait:
657 ;; as long as the value in queue-data isn't the waiting thread's id, it
658 ;; matters not what it is -- using the queue object itself is handy.
660 ;; XXX we should do something to ensure that the result of this setf
661 ;; is visible to all CPUs.
663 ;; ^-- surely futex_wake() involves a memory barrier?
666 (setf (waitqueue-token queue) queue)
667 (with-pinned-objects (queue)
668 (futex-wake (waitqueue-token-address queue) n)))))
670 (defun condition-broadcast (queue)
672 "Notify all threads waiting on QUEUE."
673 (condition-notify queue
674 ;; On a 64-bit platform truncating M-P-F to an int
675 ;; results in -1, which wakes up only one thread.
677 most-positive-fixnum)))
682 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
684 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
685 should be considered an implementation detail, and may change in the
687 (name nil :type (or null thread-name))
688 (%count 0 :type (integer 0))
689 (waitcount 0 :type sb!vm:word)
691 (queue (make-waitqueue)))
693 (setf (fdocumentation 'semaphore-name 'function)
694 "The name of the semaphore INSTANCE. Setfable.")
696 (declaim (inline semaphore-count))
697 (defun semaphore-count (instance)
698 "Returns the current count of the semaphore INSTANCE."
699 (semaphore-%count instance))
701 (defun make-semaphore (&key name (count 0))
703 "Create a semaphore with the supplied COUNT and NAME."
704 (%make-semaphore name count))
706 (defun wait-on-semaphore (semaphore)
708 "Decrement the count of SEMAPHORE if the count would not be
709 negative. Else blocks until the semaphore can be decremented."
710 ;; A more direct implementation based directly on futexes should be
713 ;; We need to disable interrupts so that we don't forget to
714 ;; decrement the waitcount (which would happen if an asynch
715 ;; interrupt should catch us on our way out from the loop.)
716 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
717 ;; Quick check: is it positive? If not, enter the wait loop.
718 (let ((count (semaphore-%count semaphore)))
720 (setf (semaphore-%count semaphore) (1- count))
723 ;; Need to use ATOMIC-INCF despite the lock, because on our
724 ;; way out from here we might not be locked anymore -- so
725 ;; another thread might be tweaking this in parallel using
726 ;; ATOMIC-DECF. No danger over overflow, since there it
727 ;; at most one increment per thread waiting on the semaphore.
728 (sb!ext:atomic-incf (semaphore-waitcount semaphore))
729 (loop until (plusp (setf count (semaphore-%count semaphore)))
730 do (condition-wait (semaphore-queue semaphore)
731 (semaphore-mutex semaphore)))
732 (setf (semaphore-%count semaphore) (1- count)))
733 ;; Need to use ATOMIC-DECF instead of DECF, as CONDITION-WAIT
734 ;; may unwind without the lock being held due to timeouts.
735 (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
737 (defun try-semaphore (semaphore &optional (n 1))
739 "Try to decrement the count of SEMAPHORE by N. If the count were to
740 become negative, punt and return NIL, otherwise return true."
741 (declare (type (integer 1) n))
742 (with-mutex ((semaphore-mutex semaphore))
743 (let ((new-count (- (semaphore-%count semaphore) n)))
744 (when (not (minusp new-count))
745 (setf (semaphore-%count semaphore) new-count)))))
747 (defun signal-semaphore (semaphore &optional (n 1))
749 "Increment the count of SEMAPHORE by N. If there are threads waiting
750 on this semaphore, then N of them is woken up."
751 (declare (type (integer 1) n))
752 ;; Need to disable interrupts so that we don't lose a wakeup after
753 ;; we have incremented the count.
754 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
755 (let ((waitcount (semaphore-waitcount semaphore))
756 (count (incf (semaphore-%count semaphore) n)))
757 (when (plusp waitcount)
758 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
761 ;;;; Job control, independent listeners
764 (lock (make-mutex :name "session lock"))
766 (interactive-threads nil)
767 (interactive-threads-queue (make-waitqueue)))
769 (defvar *session* nil)
771 ;;; The debugger itself tries to acquire the session lock, don't let
772 ;;; funny situations (like getting a sigint while holding the session
773 ;;; lock) occur. At the same time we need to allow interrupts while
774 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
775 ;;; be interruptible.
777 ;;; Take care: we sometimes need to obtain the session lock while
778 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
779 ;;; _after_ getting a session lock! (Deadlock risk.)
781 ;;; FIXME: It would be good to have ordered locks to ensure invariants
783 (defmacro with-session-lock ((session) &body body)
784 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
787 (defun new-session ()
788 (make-session :threads (list *current-thread*)
789 :interactive-threads (list *current-thread*)))
791 (defun init-job-control ()
792 (/show0 "Entering INIT-JOB-CONTROL")
793 (setf *session* (new-session))
794 (/show0 "Exiting INIT-JOB-CONTROL"))
796 (defun %delete-thread-from-session (thread session)
797 (with-session-lock (session)
798 (setf (session-threads session)
799 (delete thread (session-threads session))
800 (session-interactive-threads session)
801 (delete thread (session-interactive-threads session)))))
803 (defun call-with-new-session (fn)
804 (%delete-thread-from-session *current-thread* *session*)
805 (let ((*session* (new-session)))
808 (defmacro with-new-session (args &body forms)
809 (declare (ignore args)) ;for extensibility
810 (sb!int:with-unique-names (fb-name)
811 `(labels ((,fb-name () ,@forms))
812 (call-with-new-session (function ,fb-name)))))
814 ;;; Remove thread from its session, if it has one.
816 (defun handle-thread-exit (thread)
817 (/show0 "HANDLING THREAD EXIT")
819 (with-all-threads-lock
820 (setf (thread-%alive-p thread) nil)
821 (setf (thread-os-thread thread) nil)
822 (setq *all-threads* (delete thread *all-threads*))
824 (%delete-thread-from-session thread *session*)))
827 (/show0 "FREEING MUTEX LUTEX")
828 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
829 (%lutex-destroy lutex))))
831 (defun terminate-session ()
833 "Kill all threads in session except for this one. Does nothing if current
834 thread is not the foreground thread."
835 ;; FIXME: threads created in other threads may escape termination
837 (with-session-lock (*session*)
838 (and (eq *current-thread*
839 (car (session-interactive-threads *session*)))
840 (session-threads *session*)))))
841 ;; do the kill after dropping the mutex; unwind forms in dying
842 ;; threads may want to do session things
843 (dolist (thread to-kill)
844 (unless (eq thread *current-thread*)
845 ;; terminate the thread but don't be surprised if it has
846 ;; exited in the meantime
847 (handler-case (terminate-thread thread)
848 (interrupt-thread-error ()))))))
850 ;;; called from top of invoke-debugger
851 (defun debugger-wait-until-foreground-thread (stream)
852 "Returns T if thread had been running in background, NIL if it was
854 (declare (ignore stream))
858 (with-session-lock (*session*)
859 (not (member *current-thread*
860 (session-interactive-threads *session*))))
863 (defun get-foreground ()
866 (let ((was-foreground t))
868 (/show0 "Looping in GET-FOREGROUND")
869 (with-session-lock (*session*)
870 (let ((int-t (session-interactive-threads *session*)))
871 (when (eq (car int-t) *current-thread*)
872 (unless was-foreground
873 (format *query-io* "Resuming thread ~A~%" *current-thread*))
874 (return-from get-foreground t))
875 (setf was-foreground nil)
876 (unless (member *current-thread* int-t)
877 (setf (cdr (last int-t))
878 (list *current-thread*)))
880 (session-interactive-threads-queue *session*)
881 (session-lock *session*)))))))
883 (defun release-foreground (&optional next)
885 "Background this thread. If NEXT is supplied, arrange for it to
886 have the foreground next."
887 #!-sb-thread (declare (ignore next))
890 (with-session-lock (*session*)
891 (when (rest (session-interactive-threads *session*))
892 (setf (session-interactive-threads *session*)
893 (delete *current-thread* (session-interactive-threads *session*))))
895 (setf (session-interactive-threads *session*)
897 (delete next (session-interactive-threads *session*)))))
898 (condition-broadcast (session-interactive-threads-queue *session*))))
900 (defun foreground-thread ()
901 (car (session-interactive-threads *session*)))
903 (defun make-listener-thread (tty-name)
904 (assert (probe-file tty-name))
905 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
906 (out (sb!unix:unix-dup in))
907 (err (sb!unix:unix-dup in)))
908 (labels ((thread-repl ()
909 (sb!unix::unix-setsid)
910 (let* ((sb!impl::*stdin*
911 (make-fd-stream in :input t :buffering :line
914 (make-fd-stream out :output t :buffering :line
917 (make-fd-stream err :output t :buffering :line
920 (make-fd-stream err :input t :output t
923 (sb!impl::*descriptor-handlers* nil))
926 (sb!impl::toplevel-repl nil)
927 (sb!int:flush-standard-output-streams))))))
928 (make-thread #'thread-repl))))
933 (defun make-thread (function &key name)
935 "Create a new thread of NAME that runs FUNCTION. When the function
936 returns the thread exits. The return values of FUNCTION are kept
937 around and can be retrieved by JOIN-THREAD."
938 #!-sb-thread (declare (ignore function name))
939 #!-sb-thread (error "Not supported in unithread builds.")
941 (let* ((thread (%make-thread :name name))
942 (setup-sem (make-semaphore :name "Thread setup semaphore"))
943 (real-function (coerce function 'function))
945 (named-lambda initial-thread-function ()
946 ;; In time we'll move some of the binding presently done in C
949 ;; KLUDGE: Here we have a magic list of variables that are
950 ;; not thread-safe for one reason or another. As people
951 ;; report problems with the thread safety of certain
952 ;; variables, (e.g. "*print-case* in multiple threads
953 ;; broken", sbcl-devel 2006-07-14), we add a few more
954 ;; bindings here. The Right Thing is probably some variant
955 ;; of Allegro's *cl-default-special-bindings*, as that is at
956 ;; least accessible to users to secure their own libraries.
959 ;; As it is, this lambda must not cons until we are ready
960 ;; to run GC. Be very careful.
961 (let* ((*current-thread* thread)
962 (*restart-clusters* nil)
963 (*handler-clusters* (sb!kernel::initial-handler-clusters))
964 (*condition-restarts* nil)
965 (sb!impl::*deadline* nil)
966 (sb!impl::*deadline-seconds* nil)
967 (sb!impl::*step-out* nil)
968 ;; internal printer variables
969 (sb!impl::*previous-case* nil)
970 (sb!impl::*previous-readtable-case* nil)
971 (sb!impl::*internal-symbol-output-fun* nil)
972 (sb!impl::*descriptor-handlers* nil)) ; serve-event
974 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
975 (setf (thread-os-thread thread) (current-thread-os-thread))
976 (with-mutex ((thread-result-lock thread))
977 (with-all-threads-lock
978 (push thread *all-threads*))
979 (with-session-lock (*session*)
980 (push thread (session-threads *session*)))
981 (setf (thread-%alive-p thread) t)
982 (signal-semaphore setup-sem)
983 ;; can't use handling-end-of-the-world, because that flushes
984 ;; output streams, and we don't necessarily have any (or we
985 ;; could be sharing them)
986 (catch 'sb!impl::toplevel-catcher
987 (catch 'sb!impl::%end-of-the-world
991 "~~@<Terminate this thread (~A)~~@:>"
995 (with-local-interrupts
996 ;; Now that most things have a chance
997 ;; to work properly without messing up
998 ;; other threads, it's time to enable
1000 (sb!unix::unblock-deferrable-signals)
1001 (setf (thread-result thread)
1003 (multiple-value-list
1004 (funcall real-function))))
1005 ;; Try to block deferrables. An
1006 ;; interrupt may unwind it, but for a
1007 ;; normal exit it prevents interrupt
1009 (block-deferrable-signals))
1010 ;; We're going down, can't handle interrupts
1011 ;; sanely anymore. GC remains enabled.
1012 (block-deferrable-signals)
1013 ;; We don't want to run interrupts in a dead
1014 ;; thread when we leave WITHOUT-INTERRUPTS.
1015 ;; This potentially causes important
1016 ;; interupts to be lost: SIGINT comes to
1018 (setq *interrupt-pending* nil)
1019 (handle-thread-exit thread))))))))
1021 ;; If the starting thread is stopped for gc before it signals the
1022 ;; semaphore then we'd be stuck.
1023 (assert (not *gc-inhibit*))
1024 ;; Keep INITIAL-FUNCTION pinned until the child thread is
1025 ;; initialized properly. Wrap the whole thing in
1026 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1029 (with-pinned-objects (initial-function)
1032 (get-lisp-obj-address initial-function))))
1033 (when (zerop os-thread)
1034 (error "Can't create a new thread"))
1035 (wait-on-semaphore setup-sem)
1038 (defun join-thread (thread &key (default nil defaultp))
1040 "Suspend current thread until THREAD exits. Returns the result
1041 values of the thread function. If the thread does not exit normally,
1042 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
1043 (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
1044 (cond ((car (thread-result thread))
1045 (return-from join-thread
1046 (values-list (cdr (thread-result thread)))))
1048 (return-from join-thread default))))
1049 (error 'join-thread-error :thread thread))
1051 (defun destroy-thread (thread)
1053 "Deprecated. Same as TERMINATE-THREAD."
1054 (terminate-thread thread))
1056 (defmacro with-interruptions-lock ((thread) &body body)
1057 `(with-system-mutex ((thread-interruptions-lock ,thread))
1060 ;;; Called from the signal handler.
1062 (defun run-interruption ()
1063 (let ((interruption (with-interruptions-lock (*current-thread*)
1064 (pop (thread-interruptions *current-thread*)))))
1065 ;; If there is more to do, then resignal and let the normal
1066 ;; interrupt deferral mechanism take care of the rest. From the
1067 ;; OS's point of view the signal we are in the handler for is no
1068 ;; longer pending, so the signal will not be lost.
1069 (when (thread-interruptions *current-thread*)
1070 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1072 (funcall interruption))))
1074 (defun interrupt-thread (thread function)
1076 "Interrupt the live THREAD and make it run FUNCTION. A moderate
1077 degree of care is expected for use of INTERRUPT-THREAD, due to its
1078 nature: if you interrupt a thread that was holding important locks
1079 then do something that turns out to need those locks, you probably
1080 won't like the effect. FUNCTION runs with interrupts disabled, but
1081 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1082 enable interrupts (GET-MUTEX when contended, for instance) so the
1083 first thing to do is usually a WITH-INTERRUPTS or a
1084 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1085 run in same the order they were sent."
1087 (declare (ignore thread))
1089 (with-interrupt-bindings
1090 (with-interrupts (funcall function)))
1092 (let ((os-thread (thread-os-thread thread)))
1093 (cond ((not os-thread)
1094 (error 'interrupt-thread-error :thread thread))
1096 (with-interruptions-lock (thread)
1097 ;; Append to the end of the interruptions queue. It's
1098 ;; O(N), but it does not hurt to slow interruptors down a
1099 ;; bit when the queue gets long.
1100 (setf (thread-interruptions thread)
1101 (append (thread-interruptions thread)
1104 (allow-with-interrupts
1105 (funcall function))))))))
1106 (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1107 (error 'interrupt-thread-error :thread thread))))))
1109 (defun terminate-thread (thread)
1111 "Terminate the thread identified by THREAD, by causing it to run
1112 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1113 (interrupt-thread thread 'sb!ext:quit))
1115 (define-alien-routine "thread_yield" int)
1118 (setf (fdocumentation 'thread-yield 'function)
1119 "Yield the processor to other threads.")
1121 ;;; internal use only. If you think you need to use these, either you
1122 ;;; are an SBCL developer, are doing something that you should discuss
1123 ;;; with an SBCL developer first, or are doing something that you
1124 ;;; should probably discuss with a professional psychiatrist first
1127 (defun %thread-sap (thread)
1128 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1129 (target (thread-os-thread thread)))
1131 (when (sap= thread-sap (int-sap 0)) (return nil))
1132 (let ((os-thread (sap-ref-word thread-sap
1133 (* sb!vm:n-word-bytes
1134 sb!vm::thread-os-thread-slot))))
1135 (when (= os-thread target) (return thread-sap))
1137 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1138 sb!vm::thread-next-slot)))))))
1140 (defun %symbol-value-in-thread (symbol thread)
1141 ;; Prevent the thread from dying completely while we look for the TLS
1143 (with-all-threads-lock
1145 (if (thread-alive-p thread)
1146 (let* ((epoch sb!kernel::*gc-epoch*)
1147 (offset (* sb!vm:n-word-bytes
1148 (sb!vm::symbol-tls-index symbol)))
1149 (tl-val (sap-ref-word (%thread-sap thread) offset)))
1150 (cond ((zerop offset)
1151 (return (values nil :no-tls-value)))
1152 ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1153 (eql tl-val sb!vm:unbound-marker-widetag))
1154 (return (values nil :unbound-in-thread)))
1156 (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
1157 ;; The value we constructed may be invalid if a GC has
1158 ;; occurred. That is harmless, though, since OBJ is
1159 ;; either in a register or on stack, and we are
1160 ;; conservative on both on GENCGC -- so a bogus object
1161 ;; is safe here as long as we don't return it. If we
1162 ;; ever port threads to a non-conservative GC we must
1163 ;; pin the TL-VAL address before constructing OBJ, or
1164 ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
1166 ;; The reason we don't just rely on TL-VAL pinning the
1167 ;; object is that the call to MAKE-LISP-OBJ may cause
1168 ;; bignum allocation, at which point TL-VAL might not
1169 ;; be alive anymore -- hence the epoch check.
1170 (when (eq epoch sb!kernel::*gc-epoch*)
1172 (return (values obj :ok))
1173 (return (values obj :invalid-tls-value))))))))
1174 (return (values nil :thread-dead))))))
1176 (defun %set-symbol-value-in-thread (symbol thread value)
1177 (with-pinned-objects (value)
1178 ;; Prevent the thread from dying completely while we look for the TLS
1180 (with-all-threads-lock
1181 (if (thread-alive-p thread)
1182 (let ((offset (* sb!vm:n-word-bytes
1183 (sb!vm::symbol-tls-index symbol))))
1184 (cond ((zerop offset)
1185 (values nil :no-tls-value))
1187 (setf (sap-ref-word (%thread-sap thread) offset)
1188 (get-lisp-obj-address value))
1189 (values value :ok))))
1190 (values nil :thread-dead))))))
1192 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1193 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1196 If the value cannot be retrieved (because the thread has exited or because it
1197 has no local binding for NAME) and ERRORP is true signals an error of type
1198 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1199 NIL, and a secondary value of NIL.
1201 Can also be used with SETF to change the thread-local value of SYMBOL.
1203 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1204 mechanism for inter-thread communication."
1205 (declare (symbol symbol) (thread thread))
1207 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1211 (error 'symbol-value-in-thread-error
1214 :info (list :read status))
1218 (values (symbol-value symbol) t)
1220 (error 'symbol-value-in-thread-error
1223 :info (list :read :unbound-in-thread))
1226 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1227 (declare (symbol symbol) (thread thread))
1229 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1233 (error 'symbol-value-in-thread-error
1236 :info (list :write status))
1240 (values (setf (symbol-value symbol) value) t)
1242 (error 'symbol-value-in-thread-error
1245 :info (list :write :unbound-in-thread))
1248 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1249 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1254 (defun thread-stepping ()
1256 (sap-ref-word (current-thread-sap)
1257 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1259 (defun (setf thread-stepping) (value)
1260 (setf (sap-ref-word (current-thread-sap)
1261 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1262 (get-lisp-obj-address value)))