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 ;;; Locks don't come any simpler -- or more lightweight than this. While
17 ;;; this is probably a premature optimization for most users, we still
18 ;;; need it internally for implementing condition variables outside Futex
21 (defmacro with-cas-lock ((place) &body body)
23 "Runs BODY with interrupts disabled and *CURRENT-THREAD* compare-and-swapped
24 into PLACE instead of NIL. PLACE must be a place acceptable to
25 COMPARE-AND-SWAP, and must initially hold NIL.
27 WITH-CAS-LOCK is suitable mostly when the critical section needing protection
28 is very small, and cost of allocating a separate lock object would be
29 prohibitive. While it is the most lightweight locking constructed offered by
30 SBCL, it is also the least scalable if the section is heavily contested or
33 WITH-CAS-LOCK can be entered recursively."
35 (%with-cas-lock (,place) ,@body)))
37 (defmacro %with-cas-lock ((place) &body body &environment env)
38 (with-unique-names (owner self)
39 (multiple-value-bind (vars vals old new cas-form read-form)
40 (sb!ext:get-cas-expansion place env)
41 `(let* (,@(mapcar #'list vars vals)
45 (,self *current-thread*)
50 (unless (eq ,owner ,self)
51 (loop until (loop repeat 100
55 (not (setf ,owner ,cas-form)))
58 do (sb!ext:spin-loop-hint))
61 (unless (eq ,owner ,self)
64 (unless (eq ,old ,cas-form)
65 (bug "Failed to release CAS lock!")))))))))
69 (define-condition thread-error (error)
70 ((thread :reader thread-error-thread :initarg :thread))
73 "Conditions of type THREAD-ERROR are signalled when thread operations fail.
74 The offending thread is initialized by the :THREAD initialization argument and
75 read by the function THREAD-ERROR-THREAD."))
77 (define-condition thread-deadlock (thread-error)
78 ((cycle :initarg :cycle :reader thread-deadlock-cycle))
80 (lambda (condition stream)
81 (let ((*print-circle* t))
82 (format stream "Deadlock cycle detected:~%~@< ~@;~
84 (mapcar #'car (thread-deadlock-cycle condition)))))))
88 (fdocumentation 'thread-error-thread 'function)
89 "Return the offending thread that the THREAD-ERROR pertains to.")
91 (define-condition symbol-value-in-thread-error (cell-error thread-error)
92 ((info :reader symbol-value-in-thread-error-info :initarg :info))
94 (lambda (condition stream)
95 (destructuring-bind (op problem)
96 (symbol-value-in-thread-error-info condition)
97 (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
99 (cell-error-name condition)
100 (thread-error-thread condition)
102 (:unbound-in-thread "the symbol is unbound in thread.")
103 (:no-tls-value "the symbol has no thread-local value.")
104 (:thread-dead "the thread has exited.")
105 (:invalid-tls-value "the thread-local value is not valid."))))))
108 "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
109 the symbol not having a thread-local value, or the target thread having
110 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
111 offending thread using THREAD-ERROR-THREAD."))
113 (define-condition join-thread-error (thread-error)
114 ((problem :initarg :problem :reader join-thread-problem))
115 (:report (lambda (c s)
116 (ecase (join-thread-problem c)
118 (format s "Joining thread failed: thread ~A ~
119 did not return normally."
120 (thread-error-thread c)))
122 (format s "Joining thread timed out: thread ~A ~
123 did not exit in time."
124 (thread-error-thread c))))))
127 "Signalled when joining a thread fails due to abnormal exit of the thread
128 to be joined. The offending thread can be accessed using
129 THREAD-ERROR-THREAD."))
131 (define-deprecated-function :late "1.0.29.17" join-thread-error-thread thread-error-thread
133 (thread-error-thread condition))
135 (define-condition interrupt-thread-error (thread-error) ()
136 (:report (lambda (c s)
137 (format s "Interrupt thread failed: thread ~A has exited."
138 (thread-error-thread c))))
141 "Signalled when interrupting a thread fails because the thread has already
142 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
144 (define-deprecated-function :late "1.0.29.17" interrupt-thread-error-thread thread-error-thread
146 (thread-error-thread condition))
148 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
149 ;;; necessary because threads are only supported with the conservative
150 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
151 ;;; are treated as references.
153 ;;; set the doc here because in early-thread FDOCUMENTATION is not
156 (setf (fdocumentation '*current-thread* 'variable)
157 "Bound in each thread to the thread itself.")
161 (fdocumentation 'thread-name 'function)
162 "Name of the thread. Can be assigned to using SETF. Thread names can be
163 arbitrary printable objects, and need not be unique.")
165 (def!method print-object ((thread thread) stream)
166 (print-unreadable-object (thread stream :type t :identity t)
167 (let* ((cookie (list thread))
168 (info (if (thread-alive-p thread)
171 (join-thread thread :default cookie))))
172 (state (if (eq :running info)
175 (thread-waiting-for thread))))
178 (list "waiting on:" (cdr thing)
179 "timeout: " (car thing)))
183 (list "waiting on:" thing))))
184 (if (eq cookie (car info))
187 (values (when (eq :finished state)
191 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
197 (defun print-lock (lock name owner stream)
198 (let ((*print-circle* t))
199 (print-unreadable-object (lock stream :type t :identity (not name))
201 (format stream "~@[~S ~]~2I~_owner: ~S" name owner)
202 (format stream "~@[~S ~](free)" name)))))
204 (def!method print-object ((mutex mutex) stream)
205 (print-lock mutex (mutex-name mutex) (mutex-owner mutex) stream))
207 (defun thread-alive-p (thread)
209 "Return T if THREAD is still alive. Note that the return value is
210 potentially stale even before the function returns, as the thread may exit at
212 (thread-%alive-p thread))
214 ;; A thread is eligible for gc iff it has finished and there are no
215 ;; more references to it. This list is supposed to keep a reference to
216 ;; all running threads.
217 (defvar *all-threads* ())
218 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
220 (defvar *default-alloc-signal* nil)
222 (defmacro with-all-threads-lock (&body body)
223 `(with-system-mutex (*all-threads-lock*)
226 (defun list-all-threads ()
228 "Return a list of the live threads. Note that the return value is
229 potentially stale even before the function returns, as new threads may be
230 created and old ones may exit at any time."
231 (with-all-threads-lock
232 (copy-list *all-threads*)))
234 (declaim (inline current-thread-sap))
235 (defun current-thread-sap ()
236 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
238 (declaim (inline current-thread-os-thread))
239 (defun current-thread-os-thread ()
241 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
245 (defun init-initial-thread ()
246 (/show0 "Entering INIT-INITIAL-THREAD")
247 (let ((initial-thread (%make-thread :name "initial thread"
249 :os-thread (current-thread-os-thread))))
250 (setq *current-thread* initial-thread)
251 ;; Either *all-threads* is empty or it contains exactly one thread
252 ;; in case we are in reinit since saving core with multiple
253 ;; threads doesn't work.
254 (setq *all-threads* (list initial-thread))))
257 ;;;; Aliens, low level stuff
259 (define-alien-routine "kill_safely"
261 (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
266 ;; FIXME it would be good to define what a thread id is or isn't
267 ;; (our current assumption is that it's a fixnum). It so happens
268 ;; that on Linux it's a pid, but it might not be on posix thread
270 (define-alien-routine ("create_thread" %create-thread)
271 unsigned-long (lisp-fun-address unsigned-long))
273 (declaim (inline %block-deferrable-signals))
274 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
276 (where sb!alien:unsigned-long)
277 (old sb!alien:unsigned-long))
279 (defun block-deferrable-signals ()
280 (%block-deferrable-signals 0 0))
284 (declaim (inline futex-wait %futex-wait futex-wake))
286 (define-alien-routine ("futex_wait" %futex-wait)
287 int (word unsigned-long) (old-value unsigned-long)
288 (to-sec long) (to-usec unsigned-long))
290 (defun futex-wait (word old to-sec to-usec)
292 (%futex-wait word old to-sec to-usec)))
294 (define-alien-routine "futex_wake"
295 int (word unsigned-long) (n unsigned-long))))
297 ;;; used by debug-int.lisp to access interrupt contexts
298 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
300 (defun sb!vm::current-thread-offset-sap (n)
301 (declare (type (unsigned-byte 27) n))
302 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
303 (* n sb!vm:n-word-bytes)))
306 (defun sb!vm::current-thread-offset-sap (n)
307 (declare (type (unsigned-byte 27) n))
308 (sb!vm::current-thread-offset-sap n))
311 (defmacro with-deadlocks ((thread lock &optional (timeout nil timeoutp)) &body forms)
312 (with-unique-names (n-thread n-lock new n-timeout)
313 `(let* ((,n-thread ,thread)
315 (,n-timeout ,(when timeoutp
317 (when sb!impl::*deadline*
318 sb!impl::*deadline-seconds*))))
320 ;; Using CONS tells the rest of the system there's a
321 ;; timeout in place, so it isn't considered a deadlock.
322 (cons ,n-timeout ,n-lock)
324 (declare (dynamic-extent ,new))
325 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
326 ;; in places where interrupts should already be disabled.
329 (setf (thread-waiting-for ,n-thread) ,new)
332 ;; Interrupt handlers and GC save and restore any
333 ;; previous wait marks using WITHOUT-DEADLOCKS below.
334 (setf (thread-waiting-for ,n-thread) nil)
335 (barrier (:write))))))
340 (setf (fdocumentation 'make-mutex 'function)
342 (fdocumentation 'mutex-name 'function)
343 "The name of the mutex. Setfable.")
345 #!+(and sb-thread sb-futex)
347 (define-structure-slot-addressor mutex-state-address
350 ;; Important: current code assumes these are fixnums or other
351 ;; lisp objects that don't need pinning.
352 (defconstant +lock-free+ 0)
353 (defconstant +lock-taken+ 1)
354 (defconstant +lock-contested+ 2))
356 (defun mutex-owner (mutex)
357 "Current owner of the mutex, NIL if the mutex is free. Naturally,
358 this is racy by design (another thread may acquire the mutex after
359 this function returns), it is intended for informative purposes. For
360 testing whether the current thread is holding a mutex see
362 ;; Make sure to get the current value.
363 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
365 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
366 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
367 (defun check-deadlock ()
368 (let* ((self *current-thread*)
371 (thread-waiting-for self))))
372 (labels ((detect-deadlock (lock)
373 (let ((other-thread (mutex-%owner lock)))
374 (cond ((not other-thread))
375 ((eq self other-thread)
376 (let* ((chain (deadlock-chain self origin))
379 "~%WARNING: DEADLOCK CYCLE DETECTED:~%~@< ~@;~
382 (mapcar #'car chain))))
383 ;; Barf to stderr in case the system is too tied up
384 ;; to report the error properly -- to avoid cross-talk
385 ;; build the whole string up first.
386 (write-string barf sb!sys:*stderr*)
387 (finish-output sb!sys:*stderr*)
388 (error 'thread-deadlock
389 :thread *current-thread*
392 (let ((other-lock (progn
394 (thread-waiting-for other-thread))))
395 ;; If the thread is waiting with a timeout OTHER-LOCK
396 ;; is a cons, and we don't consider it a deadlock -- since
397 ;; it will time out on its own sooner or later.
398 (when (mutex-p other-lock)
399 (detect-deadlock other-lock)))))))
400 (deadlock-chain (thread lock)
401 (let* ((other-thread (mutex-owner lock))
402 (other-lock (when other-thread
404 (thread-waiting-for other-thread))))
405 (cond ((not other-thread)
406 ;; The deadlock is gone -- maybe someone unwound
407 ;; from the same deadlock already?
408 (return-from check-deadlock nil))
410 ;; There's a timeout -- no deadlock.
411 (return-from check-deadlock nil))
412 ((waitqueue-p other-lock)
414 (return-from check-deadlock nil))
415 ((eq self other-thread)
417 (list (list thread lock)))
420 (cons (list thread lock)
421 (deadlock-chain other-thread other-lock))
422 ;; Again, the deadlock is gone?
423 (return-from check-deadlock nil)))))))
424 ;; Timeout means there is no deadlock
425 (when (mutex-p origin)
426 (detect-deadlock origin)
429 (defun %try-mutex (mutex new-owner)
430 (declare (type mutex mutex) (optimize (speed 3)))
432 (let ((old (mutex-%owner mutex)))
433 (when (eq new-owner old)
434 (error "Recursive lock attempt ~S." mutex))
437 (error "Strange deadlock on ~S in an unithreaded build?" mutex))
440 ;; Don't even bother to try to CAS if it looks bad.
441 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
443 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
444 (when (eql +lock-free+ (sb!ext:compare-and-swap (mutex-state mutex)
447 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
449 (bug "Old owner in free mutex: ~S" prev))
453 (defun %%wait-for-mutex (mutex new-owner to-sec to-usec stop-sec stop-usec)
454 (declare (type mutex mutex) (optimize (speed 3)))
456 (declare (ignore to-sec to-usec))
462 (not (mutex-%owner mutex)))
463 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil
465 do (return-from cas t)
468 (sb!ext:spin-loop-hint))
469 ;; Check for pending interrupts.
470 (with-interrupts nil)))
471 (declare (dynamic-extent #'cas))
472 (sb!impl::%%wait-for #'cas stop-sec stop-usec))
474 ;; This is a fairly direct translation of the Mutex 2 algorithm from
475 ;; "Futexes are Tricky" by Ulrich Drepper.
477 (when (eql +lock-free+ old)
478 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
481 (bug "Old owner in free mutex: ~S" prev))
482 (return-from %%wait-for-mutex t)))))
483 (prog ((old (sb!ext:compare-and-swap (mutex-state mutex)
484 +lock-free+ +lock-taken+)))
485 ;; Got it right off the bat?
488 ;; Mark it as contested, and sleep. (Exception: it was just released.)
489 (when (or (eql +lock-contested+ old)
490 (not (eql +lock-free+
491 (sb!ext:compare-and-swap
492 (mutex-state mutex) +lock-taken+ +lock-contested+))))
493 (when (eql 1 (with-pinned-objects (mutex)
494 (futex-wait (mutex-state-address mutex)
495 (get-lisp-obj-address +lock-contested+)
498 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
500 ;; 1 = ETIMEDOUT ***DONE***
501 ;; 2 = EINTR, a spurious wakeup
502 (return-from %%wait-for-mutex nil)))
503 ;; Try to get it, still marking it as contested.
505 (sb!ext:compare-and-swap (mutex-state mutex) +lock-free+ +lock-contested+))
506 ;; Update timeout if necessary.
508 (setf (values to-sec to-usec)
509 (sb!impl::relative-decoded-times stop-sec stop-usec)))
514 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
515 (with-deadlocks (self mutex timeout)
516 (with-interrupts (check-deadlock))
519 (return-from %wait-for-mutex
520 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
523 ;; FIXME: substract elapsed time from timeout...
524 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
525 (decode-timeout timeout))
528 (defun get-mutex (mutex &optional new-owner (waitp t) (timeout nil))
530 "Deprecated in favor of GRAB-MUTEX."
531 (declare (ignorable waitp timeout))
532 (let ((new-owner (or new-owner *current-thread*)))
533 (or (%try-mutex mutex new-owner)
536 (multiple-value-call #'%wait-for-mutex
537 mutex new-owner timeout (decode-timeout timeout))))))
539 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
541 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
542 the mutex is not immediately available, sleep until it is available.
544 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
545 GRAB-MUTEX should try to acquire the lock in the contested case.
547 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
548 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
549 that GRAB-MUTEX did -not- acquire the lock.
553 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
557 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
560 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
561 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
562 allows the call to be interrupted from sleep.
564 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
565 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
566 DEADLINE-TIMEOUT if the global deadline was due already on entering
569 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
572 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
575 (declare (ignorable waitp timeout))
576 (let ((self *current-thread*))
577 (or (%try-mutex mutex self)
580 (multiple-value-call #'%wait-for-mutex
581 mutex self timeout (decode-timeout timeout))))))
583 (defun release-mutex (mutex &key (if-not-owner :punt))
585 "Release MUTEX by setting it to NIL. Wake up threads waiting for
588 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
591 If the current thread is not the owner of the mutex then it silently
592 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
593 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
594 IF-NOT-OWNER is :FORCE)."
595 (declare (type mutex mutex))
596 ;; Order matters: set owner to NIL before releasing state.
597 (let* ((self *current-thread*)
598 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
599 (unless (eq self old-owner)
601 ((:punt) (return-from release-mutex nil))
603 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
605 (setf (mutex-%owner mutex) nil)
606 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
611 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
612 ;; unsigned-byte type this can be used:
614 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
615 ;; (unless (eql old +lock-free+)
616 ;; (setf (mutex-state mutex) +lock-free+)
617 ;; (with-pinned-objects (mutex)
618 ;; (futex-wake (mutex-state-address mutex) 1))))
619 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
620 +lock-taken+ +lock-free+)))
621 (when (eql old +lock-contested+)
622 (sb!ext:compare-and-swap (mutex-state mutex)
623 +lock-contested+ +lock-free+)
624 (with-pinned-objects (mutex)
625 (futex-wake (mutex-state-address mutex) 1))))
629 ;;;; Waitqueues/condition variables
631 #!+(or (not sb-thread) sb-futex)
632 (defstruct (waitqueue (:constructor %make-waitqueue))
635 (name nil :type (or null thread-name))
639 #!+(and sb-thread (not sb-futex))
641 (defstruct (waitqueue (:constructor %make-waitqueue))
644 (name nil :type (or null thread-name))
645 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
646 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
647 ;; lock. In most cases this should be uncontested thanks to the mutex --
648 ;; the only case where that might not be true is when CONDITION-WAIT
649 ;; unwinds and %WAITQUEUE-DROP is called.
654 (defun %waitqueue-enqueue (thread queue)
655 (setf (thread-waiting-for thread) queue)
656 (let ((head (waitqueue-%head queue))
657 (tail (waitqueue-%tail queue))
660 (setf (waitqueue-%head queue) new))
662 (setf (cdr tail) new))
663 (setf (waitqueue-%tail queue) new)
665 (defun %waitqueue-drop (thread queue)
666 (setf (thread-waiting-for thread) nil)
667 (let ((head (waitqueue-%head queue)))
668 (do ((list head (cdr list))
671 (eq (car list) thread))
673 (let ((rest (cdr list)))
675 (setf (cdr prev) rest))
677 (setf (waitqueue-%head queue) rest
680 (setf (waitqueue-%tail queue) prev)))))))
682 (defun %waitqueue-wakeup (queue n)
684 (loop while (plusp n)
685 for next = (let ((head (waitqueue-%head queue))
686 (tail (waitqueue-%tail queue)))
689 (setf (waitqueue-%head queue) nil
690 (waitqueue-%tail queue) nil)
691 (setf (waitqueue-%head queue) (cdr head)))
694 do (when (eq queue (sb!ext:compare-and-swap
695 (thread-waiting-for next) queue nil))
699 (def!method print-object ((waitqueue waitqueue) stream)
700 (print-unreadable-object (waitqueue stream :type t :identity t)
701 (format stream "~@[~A~]" (waitqueue-name waitqueue))))
703 (defun make-waitqueue (&key name)
705 "Create a waitqueue."
706 (%make-waitqueue :name name))
709 (setf (fdocumentation 'waitqueue-name 'function)
710 "The name of the waitqueue. Setfable.")
712 #!+(and sb-thread sb-futex)
713 (define-structure-slot-addressor waitqueue-token-address
717 (defun condition-wait (queue mutex &key timeout)
719 "Atomically release MUTEX and start waiting on QUEUE for till another thread
720 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
721 queue, at which point we re-acquire MUTEX and return T.
723 Spurious wakeups are possible.
725 If TIMEOUT is given, it is the maximum number of seconds to wait, including
726 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
727 wakeup and re-acquisition do not occur within the given time, returns NIL
728 without re-acquiring the mutex.
730 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
732 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
733 occurred the correct way to write code that uses CONDITION-WAIT is to loop
734 around the call, checking the the associated data:
737 (defvar *queue* (make-waitqueue))
738 (defvar *lock* (make-mutex))
741 (defun pop-data (&optional timeout)
744 do (or (condition-wait *queue* *lock* :timeout timeout)
745 ;; Lock not held, must unwind without touching *data*.
746 (return-from pop-data nil)))
750 (defun push-data (data)
753 (condition-notify *queue*)))
756 (declare (ignore queue))
759 (sb!ext:wait-for nil :timeout timeout) ; Yeah...
761 (let ((me *current-thread*))
763 (assert (eq me (mutex-%owner mutex)))
764 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
765 (decode-timeout timeout)
766 (let ((status :interrupted))
767 ;; Need to disable interrupts so that we don't miss grabbing the
768 ;; mutex on our way out.
774 (%with-cas-lock ((waitqueue-%owner queue))
775 (%waitqueue-enqueue me queue))
776 (release-mutex mutex)
778 (or (flet ((wakeup ()
780 (unless (eq queue (thread-waiting-for me))
782 (declare (dynamic-extent #'wakeup))
783 (allow-with-interrupts
784 (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
787 (with-pinned-objects (queue me)
788 (setf (waitqueue-token queue) me)
789 (release-mutex mutex)
790 ;; Now we go to sleep using futex-wait. If anyone else
791 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
792 ;; this comment, it will change the token, and so futex-wait
793 ;; returns immediately instead of sleeping. Ergo, no lost
794 ;; wakeup. We may get spurious wakeups, but that's ok.
796 (case (allow-with-interrupts
797 (futex-wait (waitqueue-token-address queue)
798 (get-lisp-obj-address me)
799 ;; our way of saying "no
807 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
809 ;; 2 = EINTR, a spurious wakeup
812 (%with-cas-lock ((waitqueue-%owner queue))
813 (if (eq queue (thread-waiting-for me))
814 (%waitqueue-drop me queue)
815 (unless (eq :ok status)
816 ;; CONDITION-NOTIFY thinks we've been woken up, but really
817 ;; we're unwinding. Wake someone else up.
818 (%waitqueue-wakeup queue 1))))
819 ;; Update timeout for mutex re-aquisition.
820 (when (and (eq :ok status) to-sec)
821 (setf (values to-sec to-usec)
822 (sb!impl::relative-decoded-times stop-sec stop-usec)))
823 ;; If we ran into deadline, try to get the mutex before
824 ;; signaling. If we don't unwind it will look like a normal
825 ;; return from user perspective.
826 (when (and (eq :timeout status) deadlinep)
827 (let ((got-it (%try-mutex mutex me)))
828 (allow-with-interrupts
831 (return-from condition-wait t))
833 ;; The deadline may have changed.
834 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
835 (decode-timeout timeout))
836 (setf status :ok))))))
837 ;; Re-acquire the mutex for normal return.
838 (when (eq :ok status)
839 (unless (or (%try-mutex mutex me)
840 (allow-with-interrupts
841 (%wait-for-mutex mutex me timeout
843 stop-sec stop-usec deadlinep)))
844 (setf status :timeout)))))
846 (unless (eq :timeout status)
847 ;; The only case we return normally without re-acquiring the
848 ;; mutex is when there is a :TIMEOUT that runs out.
849 (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
851 (defun condition-notify (queue &optional (n 1))
853 "Notify N threads waiting on QUEUE.
855 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
856 must be held by this thread during this call."
858 (declare (ignore queue n))
860 (error "Not supported in unithread builds.")
862 (declare (type (and fixnum (integer 1)) n))
863 (/show0 "Entering CONDITION-NOTIFY")
867 (with-cas-lock ((waitqueue-%owner queue))
868 (%waitqueue-wakeup queue n))
871 ;; No problem if >1 thread notifies during the comment in condition-wait:
872 ;; as long as the value in queue-data isn't the waiting thread's id, it
873 ;; matters not what it is -- using the queue object itself is handy.
875 ;; XXX we should do something to ensure that the result of this setf
876 ;; is visible to all CPUs.
878 ;; ^-- surely futex_wake() involves a memory barrier?
879 (setf (waitqueue-token queue) queue)
880 (with-pinned-objects (queue)
881 (futex-wake (waitqueue-token-address queue) n)))))
883 (defun condition-broadcast (queue)
885 "Notify all threads waiting on QUEUE.
887 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
888 must be held by this thread during this call."
889 (condition-notify queue
890 ;; On a 64-bit platform truncating M-P-F to an int
891 ;; results in -1, which wakes up only one thread.
893 most-positive-fixnum)))
898 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
900 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
901 should be considered an implementation detail, and may change in the
903 (name nil :type (or null thread-name))
904 (%count 0 :type (integer 0))
905 (waitcount 0 :type sb!vm:word)
907 (queue (make-waitqueue)))
909 (setf (fdocumentation 'semaphore-name 'function)
910 "The name of the semaphore INSTANCE. Setfable.")
912 (defstruct (semaphore-notification (:constructor make-semaphore-notification ())
915 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
916 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
917 multiple threads are using the same notification object in parallel."
918 (%status nil :type boolean))
920 (setf (fdocumentation 'make-semaphore-notification 'function)
921 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
924 (declaim (inline semaphore-notification-status))
925 (defun semaphore-notification-status (semaphore-notification)
927 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
928 SEMAPHORE-NOTICATION has succeeded since the notification object was created
931 (semaphore-notification-%status semaphore-notification))
933 (declaim (inline clear-semaphore-notification))
934 (defun clear-semaphore-notification (semaphore-notification)
936 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
937 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
939 (setf (semaphore-notification-%status semaphore-notification) nil)))
941 (declaim (inline semaphore-count))
942 (defun semaphore-count (instance)
944 "Returns the current count of the semaphore INSTANCE."
946 (semaphore-%count instance))
948 (defun make-semaphore (&key name (count 0))
950 "Create a semaphore with the supplied COUNT and NAME."
951 (%make-semaphore name count))
953 (defun wait-on-semaphore (semaphore &key timeout notification)
955 "Decrement the count of SEMAPHORE if the count would not be negative. Else
956 blocks until the semaphore can be decremented. Returns T on success.
958 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
959 cannot be decremented in that time, returns NIL without decrementing the
962 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
963 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
964 decrements the count, the status is set to T."
965 (when (and notification (semaphore-notification-status notification))
966 (with-simple-restart (continue "Clear notification status and continue.")
967 (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
968 'wait-on-semaphore semaphore))
969 (clear-semaphore-notification notification))
970 ;; A more direct implementation based directly on futexes should be
973 ;; We need to disable interrupts so that we don't forget to
974 ;; decrement the waitcount (which would happen if an asynch
975 ;; interrupt should catch us on our way out from the loop.)
977 ;; FIXME: No timeout on initial mutex acquisition.
978 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
979 ;; Quick check: is it positive? If not, enter the wait loop.
980 (let ((count (semaphore-%count semaphore)))
982 (setf (semaphore-%count semaphore) (1- count))
984 (setf (semaphore-notification-%status notification) t)))
988 ;; Need to use ATOMIC-INCF despite the lock, because on our
989 ;; way out from here we might not be locked anymore -- so
990 ;; another thread might be tweaking this in parallel using
991 ;; ATOMIC-DECF. No danger over overflow, since there it
992 ;; at most one increment per thread waiting on the semaphore.
993 (sb!ext:atomic-incf (semaphore-waitcount semaphore))
994 (loop until (plusp (setf count (semaphore-%count semaphore)))
995 do (or (condition-wait (semaphore-queue semaphore)
996 (semaphore-mutex semaphore)
998 (return-from wait-on-semaphore nil)))
999 (setf (semaphore-%count semaphore) (1- count))
1001 (setf (semaphore-notification-%status notification) t)))
1002 ;; Need to use ATOMIC-DECF as we may unwind without the lock
1004 (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
1007 (defun try-semaphore (semaphore &optional (n 1) notification)
1009 "Try to decrement the count of SEMAPHORE by N. If the count were to
1010 become negative, punt and return NIL, otherwise return true.
1012 If NOTIFICATION is given it must be a semaphore notification object
1013 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1014 the status is set to T."
1015 (declare (type (integer 1) n))
1016 (when (and notification (semaphore-notification-status notification))
1017 (with-simple-restart (continue "Clear notification status and continue.")
1018 (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
1019 'try-semaphore semaphore))
1020 (clear-semaphore-notification notification))
1021 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1022 (let ((new-count (- (semaphore-%count semaphore) n)))
1023 (when (not (minusp new-count))
1024 (setf (semaphore-%count semaphore) new-count)
1026 (setf (semaphore-notifiction-%status notification) t))
1027 ;; FIXME: We don't actually document this -- should we just
1028 ;; return T, or document new count as the return?
1031 (defun signal-semaphore (semaphore &optional (n 1))
1033 "Increment the count of SEMAPHORE by N. If there are threads waiting
1034 on this semaphore, then N of them is woken up."
1035 (declare (type (integer 1) n))
1036 ;; Need to disable interrupts so that we don't lose a wakeup after
1037 ;; we have incremented the count.
1038 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1039 (let ((waitcount (semaphore-waitcount semaphore))
1040 (count (incf (semaphore-%count semaphore) n)))
1041 (when (plusp waitcount)
1042 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1045 ;;;; Job control, independent listeners
1048 (lock (make-mutex :name "session lock"))
1050 (interactive-threads nil)
1051 (interactive-threads-queue (make-waitqueue)))
1053 (defvar *session* nil)
1055 ;;; The debugger itself tries to acquire the session lock, don't let
1056 ;;; funny situations (like getting a sigint while holding the session
1057 ;;; lock) occur. At the same time we need to allow interrupts while
1058 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1059 ;;; be interruptible.
1061 ;;; Take care: we sometimes need to obtain the session lock while
1062 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1063 ;;; _after_ getting a session lock! (Deadlock risk.)
1065 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1067 (defmacro with-session-lock ((session) &body body)
1068 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1071 (defun new-session ()
1072 (make-session :threads (list *current-thread*)
1073 :interactive-threads (list *current-thread*)))
1075 (defun init-job-control ()
1076 (/show0 "Entering INIT-JOB-CONTROL")
1077 (setf *session* (new-session))
1078 (/show0 "Exiting INIT-JOB-CONTROL"))
1080 (defun %delete-thread-from-session (thread session)
1081 (with-session-lock (session)
1082 (setf (session-threads session)
1083 (delete thread (session-threads session))
1084 (session-interactive-threads session)
1085 (delete thread (session-interactive-threads session)))))
1087 (defun call-with-new-session (fn)
1088 (%delete-thread-from-session *current-thread* *session*)
1089 (let ((*session* (new-session)))
1092 (defmacro with-new-session (args &body forms)
1093 (declare (ignore args)) ;for extensibility
1094 (sb!int:with-unique-names (fb-name)
1095 `(labels ((,fb-name () ,@forms))
1096 (call-with-new-session (function ,fb-name)))))
1098 ;;; Remove thread from its session, if it has one.
1100 (defun handle-thread-exit (thread)
1101 (/show0 "HANDLING THREAD EXIT")
1102 ;; Lisp-side cleanup
1103 (with-all-threads-lock
1104 (setf (thread-%alive-p thread) nil)
1105 (setf (thread-os-thread thread) nil)
1106 (setq *all-threads* (delete thread *all-threads*))
1108 (%delete-thread-from-session thread *session*))))
1110 (defun terminate-session ()
1112 "Kill all threads in session except for this one. Does nothing if current
1113 thread is not the foreground thread."
1114 ;; FIXME: threads created in other threads may escape termination
1116 (with-session-lock (*session*)
1117 (and (eq *current-thread*
1118 (car (session-interactive-threads *session*)))
1119 (session-threads *session*)))))
1120 ;; do the kill after dropping the mutex; unwind forms in dying
1121 ;; threads may want to do session things
1122 (dolist (thread to-kill)
1123 (unless (eq thread *current-thread*)
1124 ;; terminate the thread but don't be surprised if it has
1125 ;; exited in the meantime
1126 (handler-case (terminate-thread thread)
1127 (interrupt-thread-error ()))))))
1129 ;;; called from top of invoke-debugger
1130 (defun debugger-wait-until-foreground-thread (stream)
1131 "Returns T if thread had been running in background, NIL if it was
1133 (declare (ignore stream))
1137 (with-session-lock (*session*)
1138 (not (member *current-thread*
1139 (session-interactive-threads *session*))))
1142 (defun get-foreground ()
1145 (let ((was-foreground t))
1147 (/show0 "Looping in GET-FOREGROUND")
1148 (with-session-lock (*session*)
1149 (let ((int-t (session-interactive-threads *session*)))
1150 (when (eq (car int-t) *current-thread*)
1151 (unless was-foreground
1152 (format *query-io* "Resuming thread ~A~%" *current-thread*))
1153 (return-from get-foreground t))
1154 (setf was-foreground nil)
1155 (unless (member *current-thread* int-t)
1156 (setf (cdr (last int-t))
1157 (list *current-thread*)))
1159 (session-interactive-threads-queue *session*)
1160 (session-lock *session*)))))))
1162 (defun release-foreground (&optional next)
1164 "Background this thread. If NEXT is supplied, arrange for it to
1165 have the foreground next."
1166 #!-sb-thread (declare (ignore next))
1169 (with-session-lock (*session*)
1170 (when (rest (session-interactive-threads *session*))
1171 (setf (session-interactive-threads *session*)
1172 (delete *current-thread* (session-interactive-threads *session*))))
1174 (setf (session-interactive-threads *session*)
1176 (delete next (session-interactive-threads *session*)))))
1177 (condition-broadcast (session-interactive-threads-queue *session*))))
1179 (defun foreground-thread ()
1180 (car (session-interactive-threads *session*)))
1182 (defun make-listener-thread (tty-name)
1183 (assert (probe-file tty-name))
1184 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1185 (out (sb!unix:unix-dup in))
1186 (err (sb!unix:unix-dup in)))
1187 (labels ((thread-repl ()
1188 (sb!unix::unix-setsid)
1189 (let* ((sb!impl::*stdin*
1190 (make-fd-stream in :input t :buffering :line
1193 (make-fd-stream out :output t :buffering :line
1196 (make-fd-stream err :output t :buffering :line
1199 (make-fd-stream err :input t :output t
1202 (sb!impl::*descriptor-handlers* nil))
1203 (with-new-session ()
1205 (sb!impl::toplevel-repl nil)
1206 (sb!int:flush-standard-output-streams))))))
1207 (make-thread #'thread-repl))))
1212 (defun make-thread (function &key name arguments)
1214 "Create a new thread of NAME that runs FUNCTION with the argument
1215 list designator provided (defaults to no argument). When the function
1216 returns the thread exits. The return values of FUNCTION are kept
1217 around and can be retrieved by JOIN-THREAD."
1218 #!-sb-thread (declare (ignore function name arguments))
1219 #!-sb-thread (error "Not supported in unithread builds.")
1220 #!+sb-thread (assert (or (atom arguments)
1221 (null (cdr (last arguments))))
1223 "Argument passed to ~S, ~S, is an improper list."
1224 'make-thread arguments)
1226 (let* ((thread (%make-thread :name name))
1227 (setup-sem (make-semaphore :name "Thread setup semaphore"))
1228 (real-function (coerce function 'function))
1229 (arguments (if (listp arguments)
1233 (named-lambda initial-thread-function ()
1234 ;; In time we'll move some of the binding presently done in C
1237 ;; KLUDGE: Here we have a magic list of variables that are
1238 ;; not thread-safe for one reason or another. As people
1239 ;; report problems with the thread safety of certain
1240 ;; variables, (e.g. "*print-case* in multiple threads
1241 ;; broken", sbcl-devel 2006-07-14), we add a few more
1242 ;; bindings here. The Right Thing is probably some variant
1243 ;; of Allegro's *cl-default-special-bindings*, as that is at
1244 ;; least accessible to users to secure their own libraries.
1245 ;; --njf, 2006-07-15
1247 ;; As it is, this lambda must not cons until we are ready
1248 ;; to run GC. Be very careful.
1249 (let* ((*current-thread* thread)
1250 (*restart-clusters* nil)
1251 (*handler-clusters* (sb!kernel::initial-handler-clusters))
1252 (*condition-restarts* nil)
1253 (sb!impl::*deadline* nil)
1254 (sb!impl::*deadline-seconds* nil)
1255 (sb!impl::*step-out* nil)
1256 ;; internal printer variables
1257 (sb!impl::*previous-case* nil)
1258 (sb!impl::*previous-readtable-case* nil)
1259 (sb!impl::*internal-symbol-output-fun* nil)
1260 (sb!impl::*descriptor-handlers* nil)) ; serve-event
1262 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1263 (setf (thread-os-thread thread) (current-thread-os-thread))
1264 (with-mutex ((thread-result-lock thread))
1265 (with-all-threads-lock
1266 (push thread *all-threads*))
1267 (with-session-lock (*session*)
1268 (push thread (session-threads *session*)))
1269 (setf (thread-%alive-p thread) t)
1270 (signal-semaphore setup-sem)
1271 ;; can't use handling-end-of-the-world, because that flushes
1272 ;; output streams, and we don't necessarily have any (or we
1273 ;; could be sharing them)
1274 (catch 'sb!impl::toplevel-catcher
1275 (catch 'sb!impl::%end-of-the-world
1276 (with-simple-restart
1279 "~~@<Terminate this thread (~A)~~@:>"
1283 (with-local-interrupts
1284 ;; Now that most things have a chance
1285 ;; to work properly without messing up
1286 ;; other threads, it's time to enable
1288 (sb!unix::unblock-deferrable-signals)
1289 (setf (thread-result thread)
1291 (multiple-value-list
1292 (apply real-function arguments))))
1293 ;; Try to block deferrables. An
1294 ;; interrupt may unwind it, but for a
1295 ;; normal exit it prevents interrupt
1297 (block-deferrable-signals))
1298 ;; We're going down, can't handle interrupts
1299 ;; sanely anymore. GC remains enabled.
1300 (block-deferrable-signals)
1301 ;; We don't want to run interrupts in a dead
1302 ;; thread when we leave WITHOUT-INTERRUPTS.
1303 ;; This potentially causes important
1304 ;; interupts to be lost: SIGINT comes to
1306 (setq *interrupt-pending* nil)
1307 (handle-thread-exit thread))))))))
1309 ;; If the starting thread is stopped for gc before it signals the
1310 ;; semaphore then we'd be stuck.
1311 (assert (not *gc-inhibit*))
1312 ;; Keep INITIAL-FUNCTION pinned until the child thread is
1313 ;; initialized properly. Wrap the whole thing in
1314 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1317 (with-pinned-objects (initial-function)
1320 (get-lisp-obj-address initial-function))))
1321 (when (zerop os-thread)
1322 (error "Can't create a new thread"))
1323 (wait-on-semaphore setup-sem)
1326 (defun join-thread (thread &key (default nil defaultp) timeout)
1328 "Suspend current thread until THREAD exits. Return the result values of the
1331 If the thread does not exit normally within TIMEOUT seconds return DEFAULT if
1332 given, or else signal JOIN-THREAD-ERROR.
1334 NOTE: Return convention in case of a timeout is exprimental and subject to
1336 (let ((lock (thread-result-lock thread))
1342 (allow-with-interrupts
1343 ;; Don't use the timeout if the thread is not alive anymore.
1344 (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
1345 (cond ((car (thread-result thread))
1346 (return-from join-thread
1347 (values-list (cdr (thread-result thread)))))
1349 (return-from join-thread default))
1351 (setf problem :abort)))
1353 (return-from join-thread default)))
1355 (release-mutex lock))))
1356 (error 'join-thread-error :thread thread :problem problem)))
1358 (defun destroy-thread (thread)
1360 "Deprecated. Same as TERMINATE-THREAD."
1361 (terminate-thread thread))
1363 (defmacro with-interruptions-lock ((thread) &body body)
1364 `(with-system-mutex ((thread-interruptions-lock ,thread))
1367 ;;; Called from the signal handler.
1369 (defun run-interruption ()
1370 (let ((interruption (with-interruptions-lock (*current-thread*)
1371 (pop (thread-interruptions *current-thread*)))))
1372 ;; If there is more to do, then resignal and let the normal
1373 ;; interrupt deferral mechanism take care of the rest. From the
1374 ;; OS's point of view the signal we are in the handler for is no
1375 ;; longer pending, so the signal will not be lost.
1376 (when (thread-interruptions *current-thread*)
1377 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1379 (funcall interruption))))
1381 (defun interrupt-thread (thread function)
1383 "Interrupt THREAD and make it run FUNCTION.
1385 The interrupt is asynchronous, and can occur anywhere with the exception of
1386 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1388 FUNCTION is called with interrupts disabled, under
1389 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1390 enable interrupts internally, in most cases FUNCTION should either enter
1391 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1392 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1394 When a thread receives multiple interrupts, they are executed in the order
1395 they were sent -- first in, first out.
1397 This means that a great degree of care is required to use INTERRUPT-THREAD
1398 safely and sanely in a production environment. The general recommendation is
1399 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1400 entirely from production environments -- it is simply exceedingly hard to use
1403 With those caveats in mind, what you need to know when using it:
1405 * If calling FUNCTION causes a non-local transfer of control (ie. an
1406 unwind), all normal cleanup forms will be executed.
1408 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1409 it is just as if that had happened due to a regular GO, THROW, or
1410 RETURN-FROM: the interrupted cleanup form and those following it in the
1411 same UNWIND-PROTECT do not get executed.
1413 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1414 frankly an unreasonable expectation for third party libraries, especially
1415 given that asynch-unwind-safety does not compose: a function calling
1416 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1418 This means that in order for an asych unwind to be safe, the entire
1419 callstack at the point of interruption needs to be asynch-unwind-safe.
1421 * In addition to asynch-unwind-safety you must consider the issue of
1422 re-entrancy. INTERRUPT-THREAD can cause function that are never normally
1423 called recursively to be re-entered during their dynamic contour,
1424 which may cause them to misbehave. (Consider binding of special variables,
1425 values of global variables, etc.)
1427 Take togather, these two restrict the \"safe\" things to do using
1428 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1429 interactive development use is using it to force entry to debugger to inspect
1430 the state of a thread:
1432 (interrupt-thread thread #'break)
1434 Short version: be careful out there."
1436 (declare (ignore thread))
1438 (with-interrupt-bindings
1439 (with-interrupts (funcall function)))
1441 (let ((os-thread (thread-os-thread thread)))
1442 (cond ((not os-thread)
1443 (error 'interrupt-thread-error :thread thread))
1445 (with-interruptions-lock (thread)
1446 ;; Append to the end of the interruptions queue. It's
1447 ;; O(N), but it does not hurt to slow interruptors down a
1448 ;; bit when the queue gets long.
1449 (setf (thread-interruptions thread)
1450 (append (thread-interruptions thread)
1453 (allow-with-interrupts
1454 (funcall function))))))))
1455 (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1456 (error 'interrupt-thread-error :thread thread))))))
1458 (defun terminate-thread (thread)
1460 "Terminate the thread identified by THREAD, by interrupting it and causing
1461 it to call SB-EXT:QUIT.
1463 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that eg. thread
1469 (setf foo (get-foo))
1472 ;; An interrupt occurring inside the cleanup clause
1473 ;; will cause cleanups from the current UNWIND-PROTECT
1475 (release-foo foo))))
1477 might miss calling RELEASE-FOO despite GET-FOO having returned true if the
1478 interrupt occurs inside the cleanup clause, eg. during execution of
1481 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need to use
1485 (sb-sys:without-interrupts
1488 (setf foo (sb-sys:allow-with-interrupts
1490 (sb-sys:with-local-interrupts
1493 (release-foo foo)))))
1495 Since most libraries using UNWIND-PROTECT do not do this, you should never
1496 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1497 (interrupt-thread thread 'sb!ext:quit))
1499 (define-alien-routine "thread_yield" int)
1502 (setf (fdocumentation 'thread-yield 'function)
1503 "Yield the processor to other threads.")
1505 ;;; internal use only. If you think you need to use these, either you
1506 ;;; are an SBCL developer, are doing something that you should discuss
1507 ;;; with an SBCL developer first, or are doing something that you
1508 ;;; should probably discuss with a professional psychiatrist first
1511 (defun %thread-sap (thread)
1512 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1513 (target (thread-os-thread thread)))
1515 (when (sap= thread-sap (int-sap 0)) (return nil))
1516 (let ((os-thread (sap-ref-word thread-sap
1517 (* sb!vm:n-word-bytes
1518 sb!vm::thread-os-thread-slot))))
1519 (when (= os-thread target) (return thread-sap))
1521 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1522 sb!vm::thread-next-slot)))))))
1524 (defun %symbol-value-in-thread (symbol thread)
1525 ;; Prevent the thread from dying completely while we look for the TLS
1527 (with-all-threads-lock
1529 (if (thread-alive-p thread)
1530 (let* ((offset (sb!kernel:get-lisp-obj-address
1531 (sb!vm::symbol-tls-index symbol)))
1532 (obj (sap-ref-lispobj (%thread-sap thread) offset))
1533 (tl-val (sb!kernel:get-lisp-obj-address obj)))
1534 (cond ((zerop offset)
1535 (return (values nil :no-tls-value)))
1536 ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1537 (eql tl-val sb!vm:unbound-marker-widetag))
1538 (return (values nil :unbound-in-thread)))
1540 (return (values obj :ok)))))
1541 (return (values nil :thread-dead))))))
1543 (defun %set-symbol-value-in-thread (symbol thread value)
1544 (with-pinned-objects (value)
1545 ;; Prevent the thread from dying completely while we look for the TLS
1547 (with-all-threads-lock
1548 (if (thread-alive-p thread)
1549 (let ((offset (sb!kernel:get-lisp-obj-address
1550 (sb!vm::symbol-tls-index symbol))))
1551 (cond ((zerop offset)
1552 (values nil :no-tls-value))
1554 (setf (sap-ref-lispobj (%thread-sap thread) offset)
1556 (values value :ok))))
1557 (values nil :thread-dead)))))
1559 (define-alien-variable tls-index-start unsigned-int)
1561 ;; Get values from the TLS area of the current thread.
1562 (defun %thread-local-references ()
1564 (let ((sap (%thread-sap *current-thread*)))
1565 (loop for index from tls-index-start
1566 below (symbol-value 'sb!vm::*free-tls-index*)
1567 for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1568 for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1570 (typep obj '(or fixnum character))
1572 '(#.sb!vm:no-tls-value-marker-widetag
1573 #.sb!vm:unbound-marker-widetag))
1574 (member obj seen :test #'eq))
1575 collect obj into seen
1576 finally (return seen))))))
1578 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1579 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1582 If the value cannot be retrieved (because the thread has exited or because it
1583 has no local binding for NAME) and ERRORP is true signals an error of type
1584 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1585 NIL, and a secondary value of NIL.
1587 Can also be used with SETF to change the thread-local value of SYMBOL.
1589 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1590 mechanism for inter-thread communication."
1591 (declare (symbol symbol) (thread thread))
1593 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1597 (error 'symbol-value-in-thread-error
1600 :info (list :read status))
1604 (values (symbol-value symbol) t)
1606 (error 'symbol-value-in-thread-error
1609 :info (list :read :unbound-in-thread))
1612 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1613 (declare (symbol symbol) (thread thread))
1615 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1619 (error 'symbol-value-in-thread-error
1622 :info (list :write status))
1626 (values (setf (symbol-value symbol) value) t)
1628 (error 'symbol-value-in-thread-error
1631 :info (list :write :unbound-in-thread))
1634 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1635 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1640 (defun thread-stepping ()
1642 (sap-ref-word (current-thread-sap)
1643 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1645 (defun (setf thread-stepping) (value)
1646 (setf (sap-ref-word (current-thread-sap)
1647 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1648 (get-lisp-obj-address value)))