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 (self owner)
39 ;; Take care not to multiply-evaluate anything.
41 ;; FIXME: Once we get DEFCAS this can use GET-CAS-EXPANSION.
42 (let* ((placex (sb!xc:macroexpand place env))
43 (place-op (if (consp placex)
45 (error "~S: ~S is not a valid place for ~S"
47 place 'sb!ext:compare-and-swap)))
48 (place-args (cdr placex))
49 (temps (make-gensym-list (length place-args) t))
50 (place `(,place-op ,@temps)))
51 `(let* (,@(mapcar #'list temps place-args)
52 (,self *current-thread*)
56 (unless (eq ,owner ,self)
57 (loop while (setf ,owner
59 (sb!ext:compare-and-swap ,place nil ,self)))
62 (unless (eq ,owner ,self)
63 (sb!ext:compare-and-swap ,place ,self nil)))))))
67 (define-condition thread-error (error)
68 ((thread :reader thread-error-thread :initarg :thread))
71 "Conditions of type THREAD-ERROR are signalled when thread operations fail.
72 The offending thread is initialized by the :THREAD initialization argument and
73 read by the function THREAD-ERROR-THREAD."))
75 (define-condition thread-deadlock (thread-error)
76 ((cycle :initarg :cycle :reader thread-deadlock-cycle))
78 (lambda (condition stream)
79 (let ((*print-circle* t))
80 (format stream "Deadlock cycle detected:~%~@< ~@;~
82 (mapcar #'car (thread-deadlock-cycle condition)))))))
86 (fdocumentation 'thread-error-thread 'function)
87 "Return the offending thread that the THREAD-ERROR pertains to.")
89 (define-condition symbol-value-in-thread-error (cell-error thread-error)
90 ((info :reader symbol-value-in-thread-error-info :initarg :info))
92 (lambda (condition stream)
93 (destructuring-bind (op problem)
94 (symbol-value-in-thread-error-info condition)
95 (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
97 (cell-error-name condition)
98 (thread-error-thread condition)
100 (:unbound-in-thread "the symbol is unbound in thread.")
101 (:no-tls-value "the symbol has no thread-local value.")
102 (:thread-dead "the thread has exited.")
103 (:invalid-tls-value "the thread-local value is not valid."))))))
106 "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
107 the symbol not having a thread-local value, or the target thread having
108 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
109 offending thread using THREAD-ERROR-THREAD."))
111 (define-condition join-thread-error (thread-error)
112 ((problem :initarg :problem :reader join-thread-problem))
113 (:report (lambda (c s)
114 (ecase (join-thread-problem c)
116 (format s "Joining thread failed: thread ~A ~
117 did not return normally."
118 (thread-error-thread c)))
120 (format s "Joining thread timed out: thread ~A ~
121 did not exit in time."
122 (thread-error-thread c))))))
125 "Signalled when joining a thread fails due to abnormal exit of the thread
126 to be joined. The offending thread can be accessed using
127 THREAD-ERROR-THREAD."))
129 (define-deprecated-function :late "1.0.29.17" join-thread-error-thread thread-error-thread
131 (thread-error-thread condition))
133 (define-condition interrupt-thread-error (thread-error) ()
134 (:report (lambda (c s)
135 (format s "Interrupt thread failed: thread ~A has exited."
136 (thread-error-thread c))))
139 "Signalled when interrupting a thread fails because the thread has already
140 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
142 (define-deprecated-function :late "1.0.29.17" interrupt-thread-error-thread thread-error-thread
144 (thread-error-thread condition))
146 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
147 ;;; necessary because threads are only supported with the conservative
148 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
149 ;;; are treated as references.
151 ;;; set the doc here because in early-thread FDOCUMENTATION is not
154 (setf (fdocumentation '*current-thread* 'variable)
155 "Bound in each thread to the thread itself.")
159 (fdocumentation 'thread-name 'function)
160 "Name of the thread. Can be assigned to using SETF. Thread names can be
161 arbitrary printable objects, and need not be unique.")
163 (def!method print-object ((thread thread) stream)
164 (print-unreadable-object (thread stream :type t :identity t)
165 (let* ((cookie (list thread))
166 (info (if (thread-alive-p thread)
169 (join-thread thread :default cookie))))
170 (state (if (eq :running info)
171 (let* ((thing (thread-waiting-for thread)))
174 (list "waiting on:" (cdr thing)
175 "timeout: " (car thing)))
179 (list "waiting on:" thing))))
180 (if (eq cookie (car info))
183 (values (when (eq :finished state)
187 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
193 (defun print-lock (lock name owner stream)
194 (let ((*print-circle* t))
195 (print-unreadable-object (lock stream :type t :identity (not name))
197 (format stream "~@[~S ~]~2I~_owner: ~S" name owner)
198 (format stream "~@[~S ~](free)" name)))))
200 (def!method print-object ((mutex mutex) stream)
201 (print-lock mutex (mutex-name mutex) (mutex-owner mutex) stream))
203 (defun thread-alive-p (thread)
205 "Return T if THREAD is still alive. Note that the return value is
206 potentially stale even before the function returns, as the thread may exit at
208 (thread-%alive-p thread))
210 ;; A thread is eligible for gc iff it has finished and there are no
211 ;; more references to it. This list is supposed to keep a reference to
212 ;; all running threads.
213 (defvar *all-threads* ())
214 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
216 (defvar *default-alloc-signal* nil)
218 (defmacro with-all-threads-lock (&body body)
219 `(with-system-mutex (*all-threads-lock*)
222 (defun list-all-threads ()
224 "Return a list of the live threads. Note that the return value is
225 potentially stale even before the function returns, as new threads may be
226 created and old ones may exit at any time."
227 (with-all-threads-lock
228 (copy-list *all-threads*)))
230 (declaim (inline current-thread-sap))
231 (defun current-thread-sap ()
232 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
234 (declaim (inline current-thread-os-thread))
235 (defun current-thread-os-thread ()
237 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
241 (defun init-initial-thread ()
242 (/show0 "Entering INIT-INITIAL-THREAD")
243 (let ((initial-thread (%make-thread :name "initial thread"
245 :os-thread (current-thread-os-thread))))
246 (setq *current-thread* initial-thread)
247 ;; Either *all-threads* is empty or it contains exactly one thread
248 ;; in case we are in reinit since saving core with multiple
249 ;; threads doesn't work.
250 (setq *all-threads* (list initial-thread))))
253 ;;;; Aliens, low level stuff
255 (define-alien-routine "kill_safely"
257 (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
262 ;; FIXME it would be good to define what a thread id is or isn't
263 ;; (our current assumption is that it's a fixnum). It so happens
264 ;; that on Linux it's a pid, but it might not be on posix thread
266 (define-alien-routine ("create_thread" %create-thread)
267 unsigned-long (lisp-fun-address unsigned-long))
269 (declaim (inline %block-deferrable-signals))
270 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
272 (where sb!alien:unsigned-long)
273 (old sb!alien:unsigned-long))
275 (defun block-deferrable-signals ()
276 (%block-deferrable-signals 0 0))
280 (declaim (inline futex-wait %futex-wait futex-wake))
282 (define-alien-routine ("futex_wait" %futex-wait)
283 int (word unsigned-long) (old-value unsigned-long)
284 (to-sec long) (to-usec unsigned-long))
286 (defun futex-wait (word old to-sec to-usec)
288 (%futex-wait word old to-sec to-usec)))
290 (define-alien-routine "futex_wake"
291 int (word unsigned-long) (n unsigned-long))))
293 ;;; used by debug-int.lisp to access interrupt contexts
294 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
296 (defun sb!vm::current-thread-offset-sap (n)
297 (declare (type (unsigned-byte 27) n))
298 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
299 (* n sb!vm:n-word-bytes)))
302 (defun sb!vm::current-thread-offset-sap (n)
303 (declare (type (unsigned-byte 27) n))
304 (sb!vm::current-thread-offset-sap n))
307 (defmacro with-deadlocks ((thread lock &optional (timeout nil timeoutp)) &body forms)
308 (with-unique-names (n-thread n-lock new n-timeout)
309 `(let* ((,n-thread ,thread)
311 (,n-timeout ,(when timeoutp
313 (when sb!impl::*deadline*
314 sb!impl::*deadline-seconds*))))
316 ;; Using CONS tells the rest of the system there's a
317 ;; timeout in place, so it isn't considered a deadlock.
318 (cons ,n-timeout ,n-lock)
320 (declare (dynamic-extent ,new))
321 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
322 ;; in places where interrupts should already be disabled.
325 (setf (thread-waiting-for ,n-thread) ,new)
327 ;; Interrupt handlers and GC save and restore any
328 ;; previous wait marks using WITHOUT-DEADLOCKS below.
329 (setf (thread-waiting-for ,n-thread) nil)))))
334 (setf (fdocumentation 'make-mutex 'function)
336 (fdocumentation 'mutex-name 'function)
337 "The name of the mutex. Setfable.")
339 #!+(and sb-thread sb-futex)
341 (define-structure-slot-addressor mutex-state-address
344 ;; Important: current code assumes these are fixnums or other
345 ;; lisp objects that don't need pinning.
346 (defconstant +lock-free+ 0)
347 (defconstant +lock-taken+ 1)
348 (defconstant +lock-contested+ 2))
350 (defun mutex-owner (mutex)
351 "Current owner of the mutex, NIL if the mutex is free. Naturally,
352 this is racy by design (another thread may acquire the mutex after
353 this function returns), it is intended for informative purposes. For
354 testing whether the current thread is holding a mutex see
356 ;; Make sure to get the current value.
357 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
359 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
360 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
361 (defun check-deadlock ()
362 (let* ((self *current-thread*)
363 (origin (thread-waiting-for self)))
364 (labels ((detect-deadlock (lock)
365 (let ((other-thread (mutex-%owner lock)))
366 (cond ((not other-thread))
367 ((eq self other-thread)
368 (let* ((chain (deadlock-chain self origin))
371 "~%WARNING: DEADLOCK CYCLE DETECTED:~%~@< ~@;~
374 (mapcar #'car chain))))
375 ;; Barf to stderr in case the system is too tied up
376 ;; to report the error properly -- to avoid cross-talk
377 ;; build the whole string up first.
378 (write-string barf sb!sys:*stderr*)
379 (finish-output sb!sys:*stderr*)
380 (error 'thread-deadlock
381 :thread *current-thread*
384 (let ((other-lock (thread-waiting-for other-thread)))
385 ;; If the thread is waiting with a timeout OTHER-LOCK
386 ;; is a cons, and we don't consider it a deadlock -- since
387 ;; it will time out on its own sooner or later.
388 (when (mutex-p other-lock)
389 (detect-deadlock other-lock)))))))
390 (deadlock-chain (thread lock)
391 (let* ((other-thread (mutex-owner lock))
392 (other-lock (when other-thread
393 (thread-waiting-for other-thread))))
394 (cond ((not other-thread)
395 ;; The deadlock is gone -- maybe someone unwound
396 ;; from the same deadlock already?
397 (return-from check-deadlock nil))
399 ;; There's a timeout -- no deadlock.
400 (return-from check-deadlock nil))
401 ((waitqueue-p other-lock)
403 (return-from check-deadlock nil))
404 ((eq self other-thread)
406 (list (list thread lock)))
409 (cons (list thread lock)
410 (deadlock-chain other-thread other-lock))
411 ;; Again, the deadlock is gone?
412 (return-from check-deadlock nil)))))))
413 ;; Timeout means there is no deadlock
414 (when (mutex-p origin)
415 (detect-deadlock origin)
418 (defun %try-mutex (mutex new-owner)
419 (declare (type mutex mutex) (optimize (speed 3)))
421 (let ((old (mutex-%owner mutex)))
422 (when (eq new-owner old)
423 (error "Recursive lock attempt ~S." mutex))
426 (error "Strange deadlock on ~S in an unithreaded build?" mutex))
428 (and (not (mutex-%owner mutex))
429 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
431 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
432 (when (eql +lock-free+ (sb!ext:compare-and-swap (mutex-state mutex)
435 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
437 (bug "Old owner in free mutex: ~S" prev))
441 (defun %%wait-for-mutex (mutex new-owner to-sec to-usec stop-sec stop-usec)
442 (declare (type mutex mutex) (optimize (speed 3)))
444 (declare (ignore to-sec to-usec))
448 when (and (not (mutex-%owner mutex))
449 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil
451 do (return-from cas t))
452 ;; Check for pending interrupts.
453 (with-interrupts nil)))
454 (declare (dynamic-extent #'cas))
455 (sb!impl::%%wait-for #'cas stop-sec stop-usec))
457 ;; This is a fairly direct translation of the Mutex 2 algorithm from
458 ;; "Futexes are Tricky" by Ulrich Drepper.
460 (when (eql +lock-free+ old)
461 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
464 (bug "Old owner in free mutex: ~S" prev))
465 (return-from %%wait-for-mutex t)))))
466 (prog ((old (sb!ext:compare-and-swap (mutex-state mutex)
467 +lock-free+ +lock-taken+)))
468 ;; Got it right off the bat?
471 ;; Mark it as contested, and sleep. (Exception: it was just released.)
472 (when (or (eql +lock-contested+ old)
473 (not (eql +lock-free+
474 (sb!ext:compare-and-swap
475 (mutex-state mutex) +lock-taken+ +lock-contested+))))
476 (when (eql 1 (with-pinned-objects (mutex)
477 (futex-wait (mutex-state-address mutex)
478 (get-lisp-obj-address +lock-contested+)
481 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
483 ;; 1 = ETIMEDOUT ***DONE***
484 ;; 2 = EINTR, a spurious wakeup
485 (return-from %%wait-for-mutex nil)))
486 ;; Try to get it, still marking it as contested.
488 (sb!ext:compare-and-swap (mutex-state mutex) +lock-free+ +lock-contested+))
489 ;; Update timeout if necessary.
491 (setf (values to-sec to-usec)
492 (sb!impl::relative-decoded-times stop-sec stop-usec)))
496 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
497 (with-deadlocks (self mutex timeout)
498 (with-interrupts (check-deadlock))
501 (return-from %wait-for-mutex
502 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
505 ;; FIXME: substract elapsed time from timeout...
506 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
507 (decode-timeout timeout))
510 (defun get-mutex (mutex &optional new-owner (waitp t) (timeout nil))
512 "Deprecated in favor of GRAB-MUTEX."
513 (declare (ignorable waitp timeout))
514 (let ((new-owner (or new-owner *current-thread*)))
515 (or (%try-mutex mutex new-owner)
518 (multiple-value-call #'%wait-for-mutex
519 mutex new-owner timeout (decode-timeout timeout))))))
521 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
523 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
524 the mutex is not immediately available, sleep until it is available.
526 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
527 GRAB-MUTEX should try to acquire the lock in the contested case.
529 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
530 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
531 that GRAB-MUTEX did -not- acquire the lock.
535 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
539 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
542 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
543 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
544 allows the call to be interrupted from sleep.
546 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
547 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
548 DEADLINE-TIMEOUT if the global deadline was due already on entering
551 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
554 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
557 (declare (ignorable waitp timeout))
558 (let ((self *current-thread*))
559 (or (%try-mutex mutex self)
562 (multiple-value-call #'%wait-for-mutex
563 mutex self timeout (decode-timeout timeout))))))
565 (defun release-mutex (mutex &key (if-not-owner :punt))
567 "Release MUTEX by setting it to NIL. Wake up threads waiting for
570 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
573 If the current thread is not the owner of the mutex then it silently
574 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
575 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
576 IF-NOT-OWNER is :FORCE)."
577 (declare (type mutex mutex))
578 ;; Order matters: set owner to NIL before releasing state.
579 (let* ((self *current-thread*)
580 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
581 (unless (eq self old-owner)
583 ((:punt) (return-from release-mutex nil))
585 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
587 (setf (mutex-%owner mutex) nil)
588 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
593 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
594 ;; unsigned-byte type this can be used:
596 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
597 ;; (unless (eql old +lock-free+)
598 ;; (setf (mutex-state mutex) +lock-free+)
599 ;; (with-pinned-objects (mutex)
600 ;; (futex-wake (mutex-state-address mutex) 1))))
601 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
602 +lock-taken+ +lock-free+)))
603 (when (eql old +lock-contested+)
604 (sb!ext:compare-and-swap (mutex-state mutex)
605 +lock-contested+ +lock-free+)
606 (with-pinned-objects (mutex)
607 (futex-wake (mutex-state-address mutex) 1))))
611 ;;;; Waitqueues/condition variables
613 #!+(or (not sb-thread) sb-futex)
614 (defstruct (waitqueue (:constructor %make-waitqueue))
617 (name nil :type (or null thread-name))
621 #!+(and sb-thread (not sb-futex))
623 (defstruct (waitqueue (:constructor %make-waitqueue))
626 (name nil :type (or null thread-name))
627 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
628 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
629 ;; lock. In most cases this should be uncontested thanks to the mutex --
630 ;; the only case where that might not be true is when CONDITION-WAIT
631 ;; unwinds and %WAITQUEUE-DROP is called.
636 (defun %waitqueue-enqueue (thread queue)
637 (setf (thread-waiting-for thread) queue)
638 (let ((head (waitqueue-%head queue))
639 (tail (waitqueue-%tail queue))
642 (setf (waitqueue-%head queue) new))
644 (setf (cdr tail) new))
645 (setf (waitqueue-%tail queue) new)
647 (defun %waitqueue-drop (thread queue)
648 (setf (thread-waiting-for thread) nil)
649 (let ((head (waitqueue-%head queue)))
650 (do ((list head (cdr list))
652 ((eq (car list) thread)
653 (let ((rest (cdr list)))
655 (setf (cdr prev) rest))
657 (setf (waitqueue-%head queue) rest
660 (setf (waitqueue-%tail queue) prev))))
663 (defun %waitqueue-wakeup (queue n)
665 (loop while (plusp n)
666 for next = (let ((head (waitqueue-%head queue))
667 (tail (waitqueue-%tail queue)))
670 (setf (waitqueue-%head queue) nil
671 (waitqueue-%tail queue) nil)
672 (setf (waitqueue-%head queue) (cdr head)))
675 do (when (eq queue (sb!ext:compare-and-swap (thread-waiting-for next) queue nil))
679 (def!method print-object ((waitqueue waitqueue) stream)
680 (print-unreadable-object (waitqueue stream :type t :identity t)
681 (format stream "~@[~A~]" (waitqueue-name waitqueue))))
683 (defun make-waitqueue (&key name)
685 "Create a waitqueue."
686 (%make-waitqueue :name name))
689 (setf (fdocumentation 'waitqueue-name 'function)
690 "The name of the waitqueue. Setfable.")
692 #!+(and sb-thread sb-futex)
693 (define-structure-slot-addressor waitqueue-token-address
697 (defun condition-wait (queue mutex &key timeout)
699 "Atomically release MUTEX and start waiting on QUEUE for till another thread
700 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
701 queue, at which point we re-acquire MUTEX and return T.
703 Spurious wakeups are possible.
705 If TIMEOUT is given, it is the maximum number of seconds to wait, including
706 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
707 wakeup and re-acquisition do not occur within the given time, returns NIL
708 without re-acquiring the mutex.
710 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
712 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
713 occurred the correct way to write code that uses CONDITION-WAIT is to loop
714 around the call, checking the the associated data:
717 (defvar *queue* (make-waitqueue))
718 (defvar *lock* (make-mutex))
721 (defun pop-data (&optional timeout)
724 do (or (condition-wait *queue* *lock* :timeout timeout)
725 ;; Lock not held, must unwind without touching *data*.
726 (return-from pop-data nil)))
730 (defun push-data (data)
733 (condition-notify *queue*)))
735 #!-sb-thread (declare (ignore queue timeout))
738 (wait-for nil :timeout timeout) ; Yeah...
740 (let ((me *current-thread*))
742 (assert (eq me (mutex-%owner mutex)))
743 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
744 (decode-timeout timeout)
745 (let ((status :interrupted))
746 ;; Need to disable interrupts so that we don't miss grabbing the
747 ;; mutex on our way out.
753 (%waitqueue-enqueue me queue)
754 (release-mutex mutex)
756 (or (flet ((wakeup ()
757 (when (neq queue (thread-waiting-for me))
759 (declare (dynamic-extent #'wakeup))
760 (allow-with-interrupts
761 (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
764 (with-pinned-objects (queue me)
765 (setf (waitqueue-token queue) me)
766 (release-mutex mutex)
767 ;; Now we go to sleep using futex-wait. If anyone else
768 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
769 ;; this comment, it will change the token, and so futex-wait
770 ;; returns immediately instead of sleeping. Ergo, no lost
771 ;; wakeup. We may get spurious wakeups, but that's ok.
773 (case (allow-with-interrupts
774 (futex-wait (waitqueue-token-address queue)
775 (get-lisp-obj-address me)
776 ;; our way of saying "no
784 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
786 ;; 2 = EINTR, a spurious wakeup
789 (%with-cas-lock ((waitqueue-%owner queue))
790 (if (eq queue (thread-waiting-for me))
791 (%waitqueue-drop me queue)
792 (unless (eq :ok status)
793 ;; CONDITION-NOTIFY thinks we've been woken up, but really
794 ;; we're unwinding. Wake someone else up.
795 (%waitqueue-wakeup queue 1))))
796 ;; Update timeout for mutex re-aquisition.
797 (when (and (eq :ok status) to-sec)
798 (setf (values to-sec to-usec)
799 (sb!impl::relative-decoded-times stop-sec stop-usec)))
800 ;; If we ran into deadline, try to get the mutex before
801 ;; signaling. If we don't unwind it will look like a normal
802 ;; return from user perspective.
803 (when (and (eq :timeout status) deadlinep)
804 (let ((got-it (%try-mutex mutex me)))
805 (allow-with-interrupts
808 (return-from condition-wait t))
810 ;; The deadline may have changed.
811 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
812 (decode-timeout timeout))
813 (setf status :ok))))))
814 ;; Re-acquire the mutex for normal return.
815 (when (eq :ok status)
816 (unless (or (%try-mutex mutex me)
817 (allow-with-interrupts
818 (%wait-for-mutex mutex me timeout
820 stop-sec stop-usec deadlinep)))
821 (setf status :timeout)))))
823 (unless (eq :timeout status)
824 ;; The only case we return normally without re-acquiring the
825 ;; mutex is when there is a :TIMEOUT that runs out.
826 (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
828 (defun condition-notify (queue &optional (n 1))
830 "Notify N threads waiting on QUEUE.
832 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
833 must be held by this thread during this call."
835 (declare (ignore queue n))
837 (error "Not supported in unithread builds.")
839 (declare (type (and fixnum (integer 1)) n))
840 (/show0 "Entering CONDITION-NOTIFY")
844 (with-cas-lock ((waitqueue-%owner queue))
845 (%waitqueue-wakeup queue n))
848 ;; No problem if >1 thread notifies during the comment in condition-wait:
849 ;; as long as the value in queue-data isn't the waiting thread's id, it
850 ;; matters not what it is -- using the queue object itself is handy.
852 ;; XXX we should do something to ensure that the result of this setf
853 ;; is visible to all CPUs.
855 ;; ^-- surely futex_wake() involves a memory barrier?
856 (setf (waitqueue-token queue) queue)
857 (with-pinned-objects (queue)
858 (futex-wake (waitqueue-token-address queue) n)))))
860 (defun condition-broadcast (queue)
862 "Notify all threads waiting on QUEUE.
864 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
865 must be held by this thread during this call."
866 (condition-notify queue
867 ;; On a 64-bit platform truncating M-P-F to an int
868 ;; results in -1, which wakes up only one thread.
870 most-positive-fixnum)))
875 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
877 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
878 should be considered an implementation detail, and may change in the
880 (name nil :type (or null thread-name))
881 (%count 0 :type (integer 0))
882 (waitcount 0 :type sb!vm:word)
884 (queue (make-waitqueue)))
886 (setf (fdocumentation 'semaphore-name 'function)
887 "The name of the semaphore INSTANCE. Setfable.")
889 (declaim (inline semaphore-count))
890 (defun semaphore-count (instance)
891 "Returns the current count of the semaphore INSTANCE."
893 (semaphore-%count instance))
895 (defun make-semaphore (&key name (count 0))
897 "Create a semaphore with the supplied COUNT and NAME."
898 (%make-semaphore name count))
900 (defun wait-on-semaphore (semaphore &key timeout)
902 "Decrement the count of SEMAPHORE if the count would not be negative. Else
903 blocks until the semaphore can be decremented. Returns T on success.
905 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
906 cannot be decremented in that time, returns NIL without decrementing the
908 ;; A more direct implementation based directly on futexes should be
911 ;; We need to disable interrupts so that we don't forget to
912 ;; decrement the waitcount (which would happen if an asynch
913 ;; interrupt should catch us on our way out from the loop.)
915 ;; FIXME: No timeout on initial mutex acquisition.
916 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
917 ;; Quick check: is it positive? If not, enter the wait loop.
918 (let ((count (semaphore-%count semaphore)))
920 (setf (semaphore-%count semaphore) (1- count))
923 ;; Need to use ATOMIC-INCF despite the lock, because on our
924 ;; way out from here we might not be locked anymore -- so
925 ;; another thread might be tweaking this in parallel using
926 ;; ATOMIC-DECF. No danger over overflow, since there it
927 ;; at most one increment per thread waiting on the semaphore.
928 (sb!ext:atomic-incf (semaphore-waitcount semaphore))
929 (loop until (plusp (setf count (semaphore-%count semaphore)))
930 do (or (condition-wait (semaphore-queue semaphore)
931 (semaphore-mutex semaphore)
933 (return-from wait-on-semaphore nil)))
934 (setf (semaphore-%count semaphore) (1- count)))
935 ;; Need to use ATOMIC-DECF instead of DECF, as CONDITION-WAIT
936 ;; may unwind without the lock being held due to timeouts.
937 (sb!ext:atomic-decf (semaphore-waitcount semaphore))))))
940 (defun try-semaphore (semaphore &optional (n 1))
942 "Try to decrement the count of SEMAPHORE by N. If the count were to
943 become negative, punt and return NIL, otherwise return true."
944 (declare (type (integer 1) n))
945 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
946 (let ((new-count (- (semaphore-%count semaphore) n)))
947 (when (not (minusp new-count))
948 (setf (semaphore-%count semaphore) new-count)))))
950 (defun signal-semaphore (semaphore &optional (n 1))
952 "Increment the count of SEMAPHORE by N. If there are threads waiting
953 on this semaphore, then N of them is woken up."
954 (declare (type (integer 1) n))
955 ;; Need to disable interrupts so that we don't lose a wakeup after
956 ;; we have incremented the count.
957 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
958 (let ((waitcount (semaphore-waitcount semaphore))
959 (count (incf (semaphore-%count semaphore) n)))
960 (when (plusp waitcount)
961 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
964 ;;;; Job control, independent listeners
967 (lock (make-mutex :name "session lock"))
969 (interactive-threads nil)
970 (interactive-threads-queue (make-waitqueue)))
972 (defvar *session* nil)
974 ;;; The debugger itself tries to acquire the session lock, don't let
975 ;;; funny situations (like getting a sigint while holding the session
976 ;;; lock) occur. At the same time we need to allow interrupts while
977 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
978 ;;; be interruptible.
980 ;;; Take care: we sometimes need to obtain the session lock while
981 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
982 ;;; _after_ getting a session lock! (Deadlock risk.)
984 ;;; FIXME: It would be good to have ordered locks to ensure invariants
986 (defmacro with-session-lock ((session) &body body)
987 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
990 (defun new-session ()
991 (make-session :threads (list *current-thread*)
992 :interactive-threads (list *current-thread*)))
994 (defun init-job-control ()
995 (/show0 "Entering INIT-JOB-CONTROL")
996 (setf *session* (new-session))
997 (/show0 "Exiting INIT-JOB-CONTROL"))
999 (defun %delete-thread-from-session (thread session)
1000 (with-session-lock (session)
1001 (setf (session-threads session)
1002 (delete thread (session-threads session))
1003 (session-interactive-threads session)
1004 (delete thread (session-interactive-threads session)))))
1006 (defun call-with-new-session (fn)
1007 (%delete-thread-from-session *current-thread* *session*)
1008 (let ((*session* (new-session)))
1011 (defmacro with-new-session (args &body forms)
1012 (declare (ignore args)) ;for extensibility
1013 (sb!int:with-unique-names (fb-name)
1014 `(labels ((,fb-name () ,@forms))
1015 (call-with-new-session (function ,fb-name)))))
1017 ;;; Remove thread from its session, if it has one.
1019 (defun handle-thread-exit (thread)
1020 (/show0 "HANDLING THREAD EXIT")
1021 ;; Lisp-side cleanup
1022 (with-all-threads-lock
1023 (setf (thread-%alive-p thread) nil)
1024 (setf (thread-os-thread thread) nil)
1025 (setq *all-threads* (delete thread *all-threads*))
1027 (%delete-thread-from-session thread *session*))))
1029 (defun terminate-session ()
1031 "Kill all threads in session except for this one. Does nothing if current
1032 thread is not the foreground thread."
1033 ;; FIXME: threads created in other threads may escape termination
1035 (with-session-lock (*session*)
1036 (and (eq *current-thread*
1037 (car (session-interactive-threads *session*)))
1038 (session-threads *session*)))))
1039 ;; do the kill after dropping the mutex; unwind forms in dying
1040 ;; threads may want to do session things
1041 (dolist (thread to-kill)
1042 (unless (eq thread *current-thread*)
1043 ;; terminate the thread but don't be surprised if it has
1044 ;; exited in the meantime
1045 (handler-case (terminate-thread thread)
1046 (interrupt-thread-error ()))))))
1048 ;;; called from top of invoke-debugger
1049 (defun debugger-wait-until-foreground-thread (stream)
1050 "Returns T if thread had been running in background, NIL if it was
1052 (declare (ignore stream))
1056 (with-session-lock (*session*)
1057 (not (member *current-thread*
1058 (session-interactive-threads *session*))))
1061 (defun get-foreground ()
1064 (let ((was-foreground t))
1066 (/show0 "Looping in GET-FOREGROUND")
1067 (with-session-lock (*session*)
1068 (let ((int-t (session-interactive-threads *session*)))
1069 (when (eq (car int-t) *current-thread*)
1070 (unless was-foreground
1071 (format *query-io* "Resuming thread ~A~%" *current-thread*))
1072 (return-from get-foreground t))
1073 (setf was-foreground nil)
1074 (unless (member *current-thread* int-t)
1075 (setf (cdr (last int-t))
1076 (list *current-thread*)))
1078 (session-interactive-threads-queue *session*)
1079 (session-lock *session*)))))))
1081 (defun release-foreground (&optional next)
1083 "Background this thread. If NEXT is supplied, arrange for it to
1084 have the foreground next."
1085 #!-sb-thread (declare (ignore next))
1088 (with-session-lock (*session*)
1089 (when (rest (session-interactive-threads *session*))
1090 (setf (session-interactive-threads *session*)
1091 (delete *current-thread* (session-interactive-threads *session*))))
1093 (setf (session-interactive-threads *session*)
1095 (delete next (session-interactive-threads *session*)))))
1096 (condition-broadcast (session-interactive-threads-queue *session*))))
1098 (defun foreground-thread ()
1099 (car (session-interactive-threads *session*)))
1101 (defun make-listener-thread (tty-name)
1102 (assert (probe-file tty-name))
1103 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1104 (out (sb!unix:unix-dup in))
1105 (err (sb!unix:unix-dup in)))
1106 (labels ((thread-repl ()
1107 (sb!unix::unix-setsid)
1108 (let* ((sb!impl::*stdin*
1109 (make-fd-stream in :input t :buffering :line
1112 (make-fd-stream out :output t :buffering :line
1115 (make-fd-stream err :output t :buffering :line
1118 (make-fd-stream err :input t :output t
1121 (sb!impl::*descriptor-handlers* nil))
1122 (with-new-session ()
1124 (sb!impl::toplevel-repl nil)
1125 (sb!int:flush-standard-output-streams))))))
1126 (make-thread #'thread-repl))))
1131 (defun make-thread (function &key name arguments)
1133 "Create a new thread of NAME that runs FUNCTION with the argument
1134 list designator provided (defaults to no argument). When the function
1135 returns the thread exits. The return values of FUNCTION are kept
1136 around and can be retrieved by JOIN-THREAD."
1137 #!-sb-thread (declare (ignore function name arguments))
1138 #!-sb-thread (error "Not supported in unithread builds.")
1139 #!+sb-thread (assert (or (atom arguments)
1140 (null (cdr (last arguments))))
1142 "Argument passed to ~S, ~S, is an improper list."
1143 'make-thread arguments)
1145 (let* ((thread (%make-thread :name name))
1146 (setup-sem (make-semaphore :name "Thread setup semaphore"))
1147 (real-function (coerce function 'function))
1148 (arguments (if (listp arguments)
1152 (named-lambda initial-thread-function ()
1153 ;; In time we'll move some of the binding presently done in C
1156 ;; KLUDGE: Here we have a magic list of variables that are
1157 ;; not thread-safe for one reason or another. As people
1158 ;; report problems with the thread safety of certain
1159 ;; variables, (e.g. "*print-case* in multiple threads
1160 ;; broken", sbcl-devel 2006-07-14), we add a few more
1161 ;; bindings here. The Right Thing is probably some variant
1162 ;; of Allegro's *cl-default-special-bindings*, as that is at
1163 ;; least accessible to users to secure their own libraries.
1164 ;; --njf, 2006-07-15
1166 ;; As it is, this lambda must not cons until we are ready
1167 ;; to run GC. Be very careful.
1168 (let* ((*current-thread* thread)
1169 (*restart-clusters* nil)
1170 (*handler-clusters* (sb!kernel::initial-handler-clusters))
1171 (*condition-restarts* nil)
1172 (sb!impl::*deadline* nil)
1173 (sb!impl::*deadline-seconds* nil)
1174 (sb!impl::*step-out* nil)
1175 ;; internal printer variables
1176 (sb!impl::*previous-case* nil)
1177 (sb!impl::*previous-readtable-case* nil)
1178 (sb!impl::*internal-symbol-output-fun* nil)
1179 (sb!impl::*descriptor-handlers* nil)) ; serve-event
1181 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1182 (setf (thread-os-thread thread) (current-thread-os-thread))
1183 (with-mutex ((thread-result-lock thread))
1184 (with-all-threads-lock
1185 (push thread *all-threads*))
1186 (with-session-lock (*session*)
1187 (push thread (session-threads *session*)))
1188 (setf (thread-%alive-p thread) t)
1189 (signal-semaphore setup-sem)
1190 ;; can't use handling-end-of-the-world, because that flushes
1191 ;; output streams, and we don't necessarily have any (or we
1192 ;; could be sharing them)
1193 (catch 'sb!impl::toplevel-catcher
1194 (catch 'sb!impl::%end-of-the-world
1195 (with-simple-restart
1198 "~~@<Terminate this thread (~A)~~@:>"
1202 (with-local-interrupts
1203 ;; Now that most things have a chance
1204 ;; to work properly without messing up
1205 ;; other threads, it's time to enable
1207 (sb!unix::unblock-deferrable-signals)
1208 (setf (thread-result thread)
1210 (multiple-value-list
1211 (apply real-function arguments))))
1212 ;; Try to block deferrables. An
1213 ;; interrupt may unwind it, but for a
1214 ;; normal exit it prevents interrupt
1216 (block-deferrable-signals))
1217 ;; We're going down, can't handle interrupts
1218 ;; sanely anymore. GC remains enabled.
1219 (block-deferrable-signals)
1220 ;; We don't want to run interrupts in a dead
1221 ;; thread when we leave WITHOUT-INTERRUPTS.
1222 ;; This potentially causes important
1223 ;; interupts to be lost: SIGINT comes to
1225 (setq *interrupt-pending* nil)
1226 (handle-thread-exit thread))))))))
1228 ;; If the starting thread is stopped for gc before it signals the
1229 ;; semaphore then we'd be stuck.
1230 (assert (not *gc-inhibit*))
1231 ;; Keep INITIAL-FUNCTION pinned until the child thread is
1232 ;; initialized properly. Wrap the whole thing in
1233 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1236 (with-pinned-objects (initial-function)
1239 (get-lisp-obj-address initial-function))))
1240 (when (zerop os-thread)
1241 (error "Can't create a new thread"))
1242 (wait-on-semaphore setup-sem)
1245 (defun join-thread (thread &key (default nil defaultp) timeout)
1247 "Suspend current thread until THREAD exits. Return the result values of the
1250 If the thread does not exit normally within TIMEOUT seconds return DEFAULT if
1251 given, or else signal JOIN-THREAD-ERROR.
1253 NOTE: Return convention in case of a timeout is exprimental and subject to
1255 (let ((lock (thread-result-lock thread))
1261 (allow-with-interrupts
1262 ;; Don't use the timeout if the thread is not alive anymore.
1263 (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
1264 (cond ((car (thread-result thread))
1265 (return-from join-thread
1266 (values-list (cdr (thread-result thread)))))
1268 (return-from join-thread default))
1270 (setf problem :abort)))
1272 (return-from join-thread default)))
1274 (release-mutex lock))))
1275 (error 'join-thread-error :thread thread :problem problem)))
1277 (defun destroy-thread (thread)
1279 "Deprecated. Same as TERMINATE-THREAD."
1280 (terminate-thread thread))
1282 (defmacro with-interruptions-lock ((thread) &body body)
1283 `(with-system-mutex ((thread-interruptions-lock ,thread))
1286 ;;; Called from the signal handler.
1288 (defun run-interruption ()
1289 (let ((interruption (with-interruptions-lock (*current-thread*)
1290 (pop (thread-interruptions *current-thread*)))))
1291 ;; If there is more to do, then resignal and let the normal
1292 ;; interrupt deferral mechanism take care of the rest. From the
1293 ;; OS's point of view the signal we are in the handler for is no
1294 ;; longer pending, so the signal will not be lost.
1295 (when (thread-interruptions *current-thread*)
1296 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1298 (funcall interruption))))
1300 (defun interrupt-thread (thread function)
1302 "Interrupt the live THREAD and make it run FUNCTION. A moderate
1303 degree of care is expected for use of INTERRUPT-THREAD, due to its
1304 nature: if you interrupt a thread that was holding important locks
1305 then do something that turns out to need those locks, you probably
1306 won't like the effect. FUNCTION runs with interrupts disabled, but
1307 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
1308 enable interrupts (GET-MUTEX when contended, for instance) so the
1309 first thing to do is usually a WITH-INTERRUPTS or a
1310 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
1311 run in same the order they were sent."
1313 (declare (ignore thread))
1315 (with-interrupt-bindings
1316 (with-interrupts (funcall function)))
1318 (let ((os-thread (thread-os-thread thread)))
1319 (cond ((not os-thread)
1320 (error 'interrupt-thread-error :thread thread))
1322 (with-interruptions-lock (thread)
1323 ;; Append to the end of the interruptions queue. It's
1324 ;; O(N), but it does not hurt to slow interruptors down a
1325 ;; bit when the queue gets long.
1326 (setf (thread-interruptions thread)
1327 (append (thread-interruptions thread)
1330 (allow-with-interrupts
1331 (funcall function))))))))
1332 (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1333 (error 'interrupt-thread-error :thread thread))))))
1335 (defun terminate-thread (thread)
1337 "Terminate the thread identified by THREAD, by causing it to run
1338 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1339 (interrupt-thread thread 'sb!ext:quit))
1341 (define-alien-routine "thread_yield" int)
1344 (setf (fdocumentation 'thread-yield 'function)
1345 "Yield the processor to other threads.")
1347 ;;; internal use only. If you think you need to use these, either you
1348 ;;; are an SBCL developer, are doing something that you should discuss
1349 ;;; with an SBCL developer first, or are doing something that you
1350 ;;; should probably discuss with a professional psychiatrist first
1353 (defun %thread-sap (thread)
1354 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1355 (target (thread-os-thread thread)))
1357 (when (sap= thread-sap (int-sap 0)) (return nil))
1358 (let ((os-thread (sap-ref-word thread-sap
1359 (* sb!vm:n-word-bytes
1360 sb!vm::thread-os-thread-slot))))
1361 (when (= os-thread target) (return thread-sap))
1363 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1364 sb!vm::thread-next-slot)))))))
1366 (defun %symbol-value-in-thread (symbol thread)
1367 ;; Prevent the thread from dying completely while we look for the TLS
1369 (with-all-threads-lock
1371 (if (thread-alive-p thread)
1372 (let* ((epoch sb!kernel::*gc-epoch*)
1373 (offset (sb!kernel:get-lisp-obj-address
1374 (sb!vm::symbol-tls-index symbol)))
1375 (tl-val (sap-ref-word (%thread-sap thread) offset)))
1376 (cond ((zerop offset)
1377 (return (values nil :no-tls-value)))
1378 ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1379 (eql tl-val sb!vm:unbound-marker-widetag))
1380 (return (values nil :unbound-in-thread)))
1382 (multiple-value-bind (obj ok) (make-lisp-obj tl-val nil)
1383 ;; The value we constructed may be invalid if a GC has
1384 ;; occurred. That is harmless, though, since OBJ is
1385 ;; either in a register or on stack, and we are
1386 ;; conservative on both on GENCGC -- so a bogus object
1387 ;; is safe here as long as we don't return it. If we
1388 ;; ever port threads to a non-conservative GC we must
1389 ;; pin the TL-VAL address before constructing OBJ, or
1390 ;; make WITH-ALL-THREADS-LOCK imply WITHOUT-GCING.
1392 ;; The reason we don't just rely on TL-VAL pinning the
1393 ;; object is that the call to MAKE-LISP-OBJ may cause
1394 ;; bignum allocation, at which point TL-VAL might not
1395 ;; be alive anymore -- hence the epoch check.
1396 (when (eq epoch sb!kernel::*gc-epoch*)
1398 (return (values obj :ok))
1399 (return (values obj :invalid-tls-value))))))))
1400 (return (values nil :thread-dead))))))
1402 (defun %set-symbol-value-in-thread (symbol thread value)
1403 (with-pinned-objects (value)
1404 ;; Prevent the thread from dying completely while we look for the TLS
1406 (with-all-threads-lock
1407 (if (thread-alive-p thread)
1408 (let ((offset (sb!kernel:get-lisp-obj-address
1409 (sb!vm::symbol-tls-index symbol))))
1410 (cond ((zerop offset)
1411 (values nil :no-tls-value))
1413 (setf (sap-ref-word (%thread-sap thread) offset)
1414 (get-lisp-obj-address value))
1415 (values value :ok))))
1416 (values nil :thread-dead)))))
1418 (define-alien-variable tls-index-start unsigned-int)
1420 ;; Get values from the TLS area of the current thread.
1421 (defun %thread-local-references ()
1423 (let ((sap (%thread-sap *current-thread*)))
1424 (loop for index from tls-index-start
1425 below (symbol-value 'sb!vm::*free-tls-index*)
1426 for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1427 for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1429 (typep obj '(or fixnum character))
1431 '(#.sb!vm:no-tls-value-marker-widetag
1432 #.sb!vm:unbound-marker-widetag))
1433 (member obj seen :test #'eq))
1434 collect obj into seen
1435 finally (return seen))))))
1437 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1438 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1441 If the value cannot be retrieved (because the thread has exited or because it
1442 has no local binding for NAME) and ERRORP is true signals an error of type
1443 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1444 NIL, and a secondary value of NIL.
1446 Can also be used with SETF to change the thread-local value of SYMBOL.
1448 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1449 mechanism for inter-thread communication."
1450 (declare (symbol symbol) (thread thread))
1452 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1456 (error 'symbol-value-in-thread-error
1459 :info (list :read status))
1463 (values (symbol-value symbol) t)
1465 (error 'symbol-value-in-thread-error
1468 :info (list :read :unbound-in-thread))
1471 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1472 (declare (symbol symbol) (thread thread))
1474 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1478 (error 'symbol-value-in-thread-error
1481 :info (list :write status))
1485 (values (setf (symbol-value symbol) value) t)
1487 (error 'symbol-value-in-thread-error
1490 :info (list :write :unbound-in-thread))
1493 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1494 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1499 (defun thread-stepping ()
1501 (sap-ref-word (current-thread-sap)
1502 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1504 (defun (setf thread-stepping) (value)
1505 (setf (sap-ref-word (current-thread-sap)
1506 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1507 (get-lisp-obj-address value)))