Deprecation declarations for various already deprecated things
[sbcl.git] / src / code / target-thread.lisp
blob8d4382a3854b3c1894917f85181452fd47aec69e
1 ;;;; support for threads in the target machine
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!THREAD")
14 ;;; CAS Lock
15 ;;;
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
19 ;;; builds.
21 (defmacro with-cas-lock ((place) &body body)
22 #!+sb-doc
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
31 long.
33 WITH-CAS-LOCK can be entered recursively."
34 `(without-interrupts
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)
42 (,owner (progn
43 (barrier (:read))
44 ,read-form))
45 (,self *current-thread*)
46 (,old nil)
47 (,new ,self))
48 (unwind-protect
49 (progn
50 (unless (eq ,owner ,self)
51 (loop until (loop repeat 100
52 when (and (progn
53 (barrier (:read))
54 (not ,read-form))
55 (not (setf ,owner ,cas-form)))
56 return t
57 else
58 do (sb!ext:spin-loop-hint))
59 do (thread-yield)))
60 ,@body)
61 (unless (eq ,owner ,self)
62 (let ((,old ,self)
63 (,new nil))
64 (unless (eq ,old ,cas-form)
65 (bug "Failed to release CAS lock!")))))))))
67 ;;; Conditions
69 (define-condition thread-error (error)
70 ((thread :reader thread-error-thread :initarg :thread))
71 #!+sb-doc
72 (:documentation
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 simple-thread-error (thread-error simple-condition)
78 ())
80 (define-condition thread-deadlock (thread-error)
81 ((cycle :initarg :cycle :reader thread-deadlock-cycle))
82 (:report
83 (lambda (condition stream)
84 (let* ((*print-circle* t)
85 (cycle (thread-deadlock-cycle condition))
86 (start (caar cycle)))
87 (format stream "Deadlock cycle detected:~%")
88 (loop for part = (pop cycle)
89 while part
90 do (format stream " ~S~% waited for:~% ~S~% owned by:~%"
91 (car part)
92 (cdr part)))
93 (format stream " ~S~%" start)))))
95 #!+sb-doc
96 (setf
97 (fdocumentation 'thread-error-thread 'function)
98 "Return the offending thread that the THREAD-ERROR pertains to.")
100 (define-condition symbol-value-in-thread-error (cell-error thread-error)
101 ((info :reader symbol-value-in-thread-error-info :initarg :info))
102 (:report
103 (lambda (condition stream)
104 (destructuring-bind (op problem)
105 (symbol-value-in-thread-error-info condition)
106 (format stream "Cannot ~(~A~) value of ~S in ~S: ~S"
108 (cell-error-name condition)
109 (thread-error-thread condition)
110 (ecase problem
111 (:unbound-in-thread "the symbol is unbound in thread.")
112 (:no-tls-value "the symbol has no thread-local value.")
113 (:thread-dead "the thread has exited.")
114 (:invalid-tls-value "the thread-local value is not valid."))))))
115 #!+sb-doc
116 (:documentation
117 "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
118 the symbol not having a thread-local value, or the target thread having
119 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
120 offending thread using THREAD-ERROR-THREAD."))
122 (define-condition join-thread-error (thread-error)
123 ((problem :initarg :problem :reader join-thread-problem))
124 (:report (lambda (c s)
125 (ecase (join-thread-problem c)
126 (:abort
127 (format s "Joining thread failed: thread ~A ~
128 did not return normally."
129 (thread-error-thread c)))
130 (:timeout
131 (format s "Joining thread timed out: thread ~A ~
132 did not exit in time."
133 (thread-error-thread c))))))
134 #!+sb-doc
135 (:documentation
136 "Signalled when joining a thread fails due to abnormal exit of the thread
137 to be joined. The offending thread can be accessed using
138 THREAD-ERROR-THREAD."))
140 (define-deprecated-function :late "1.0.29.17" join-thread-error-thread thread-error-thread
141 (condition)
142 (thread-error-thread condition))
144 (define-condition interrupt-thread-error (thread-error) ()
145 (:report (lambda (c s)
146 (format s "Interrupt thread failed: thread ~A has exited."
147 (thread-error-thread c))))
148 #!+sb-doc
149 (:documentation
150 "Signalled when interrupting a thread fails because the thread has already
151 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
153 (define-deprecated-function :late "1.0.29.17" interrupt-thread-error-thread thread-error-thread
154 (condition)
155 (thread-error-thread condition))
157 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
158 ;;; necessary because threads are only supported with the conservative
159 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
160 ;;; are treated as references.
162 ;;; set the doc here because in early-thread FDOCUMENTATION is not
163 ;;; available, yet
164 #!+sb-doc
165 (setf (fdocumentation '*current-thread* 'variable)
166 "Bound in each thread to the thread itself.")
168 #!+sb-doc
169 (setf
170 (fdocumentation 'thread-name 'function)
171 "Name of the thread. Can be assigned to using SETF. Thread names can be
172 arbitrary printable objects, and need not be unique.")
174 (def!method print-object ((thread thread) stream)
175 (print-unreadable-object (thread stream :type t :identity t)
176 (let* ((cookie (list thread))
177 (info (if (thread-alive-p thread)
178 :running
179 (multiple-value-list
180 (join-thread thread :default cookie))))
181 (state (if (eq :running info)
182 (let* ((thing (progn
183 (barrier (:read))
184 (thread-waiting-for thread))))
185 (typecase thing
186 (cons
187 (list "waiting on:" (cdr thing)
188 "timeout: " (car thing)))
189 (null
190 (list info))
192 (list "waiting on:" thing))))
193 (if (eq cookie (car info))
194 (list :aborted)
195 :finished)))
196 (values (when (eq :finished state)
197 info))
198 (*print-level* 4))
199 (format stream
200 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
201 (thread-name thread)
202 (eq :finished state)
203 state
204 values))))
206 (defun print-lock (lock name owner stream)
207 (let ((*print-circle* t))
208 (print-unreadable-object (lock stream :type t :identity (not name))
209 (if owner
210 (format stream "~@[~S ~]~2I~_owner: ~S" name owner)
211 (format stream "~@[~S ~](free)" name)))))
213 (def!method print-object ((mutex mutex) stream)
214 (print-lock mutex (mutex-name mutex) (mutex-owner mutex) stream))
216 (defun thread-alive-p (thread)
217 #!+sb-doc
218 "Return T if THREAD is still alive. Note that the return value is
219 potentially stale even before the function returns, as the thread may exit at
220 any time."
221 (thread-%alive-p thread))
223 (defun thread-ephemeral-p (thread)
224 #!+sb-doc
225 "Return T if THREAD is `ephemeral', which indicates that this thread is
226 used by SBCL for internal purposes, and specifically that it knows how to
227 to terminate this thread cleanly prior to core file saving without signalling
228 an error in that case."
229 (thread-%ephemeral-p thread))
231 ;; A thread is eligible for gc iff it has finished and there are no
232 ;; more references to it. This list is supposed to keep a reference to
233 ;; all running threads.
234 (defvar *all-threads* ())
235 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
237 (defvar *default-alloc-signal* nil)
239 (defmacro with-all-threads-lock (&body body)
240 `(with-system-mutex (*all-threads-lock*)
241 ,@body))
243 (defun list-all-threads ()
244 #!+sb-doc
245 "Return a list of the live threads. Note that the return value is
246 potentially stale even before the function returns, as new threads may be
247 created and old ones may exit at any time."
248 (with-all-threads-lock
249 (copy-list *all-threads*)))
251 (declaim (inline current-thread-sap))
252 (defun current-thread-sap ()
253 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
255 (declaim (inline current-thread-os-thread))
256 (defun current-thread-os-thread ()
257 #!+sb-thread
258 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
259 #!-sb-thread
262 (defvar *initial-thread* nil)
263 (defvar *make-thread-lock*)
265 (defun init-initial-thread ()
266 (/show0 "Entering INIT-INITIAL-THREAD")
267 (setf sb!impl::*exit-lock* (make-mutex :name "Exit Lock")
268 *make-thread-lock* (make-mutex :name "Make-Thread Lock"))
269 (let ((initial-thread (%make-thread :name "main thread"
270 :%alive-p t)))
271 (setf (thread-os-thread initial-thread) (current-thread-os-thread)
272 *initial-thread* initial-thread
273 *current-thread* initial-thread)
274 (grab-mutex (thread-result-lock *initial-thread*))
275 ;; Either *all-threads* is empty or it contains exactly one thread
276 ;; in case we are in reinit since saving core with multiple
277 ;; threads doesn't work.
278 (setq *all-threads* (list initial-thread))))
280 (defun main-thread ()
281 #!+sb-doc
282 "Returns the main thread of the process."
283 *initial-thread*)
285 (defun main-thread-p (&optional (thread *current-thread*))
286 #!+sb-doc
287 "True if THREAD, defaulting to current thread, is the main thread of the process."
288 (eq thread *initial-thread*))
290 (defmacro return-from-thread (values-form &key allow-exit)
291 #!+sb-doc
292 "Unwinds from and terminates the current thread, with values from
293 VALUES-FORM as the results visible to JOIN-THREAD.
295 If current thread is the main thread of the process (see
296 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
297 terminating the main thread would terminate the entire process. If
298 ALLOW-EXIT is true, returning from the main thread is equivalent to
299 calling SB-EXT:EXIT with :CODE 0 and :ABORT NIL.
301 See also: ABORT-THREAD and SB-EXT:EXIT."
302 `(%return-from-thread (multiple-value-list ,values-form) ,allow-exit))
304 (defun %return-from-thread (values allow-exit)
305 (let ((self *current-thread*))
306 (cond ((main-thread-p self)
307 (unless allow-exit
308 (error 'simple-thread-error
309 :format-control "~@<Tried to return ~S as values from main thread, ~
310 but exit was not allowed.~:@>"
311 :format-arguments (list values)
312 :thread self))
313 (sb!ext:exit :code 0))
315 (throw '%return-from-thread (values-list values))))))
317 (defun abort-thread (&key allow-exit)
318 #!+sb-doc
319 "Unwinds from and terminates the current thread abnormally, causing
320 JOIN-THREAD on current thread to signal an error unless a
321 default-value is provided.
323 If current thread is the main thread of the process (see
324 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
325 terminating the main thread would terminate the entire process. If
326 ALLOW-EXIT is true, aborting the main thread is equivalent to calling
327 SB-EXT:EXIT code 1 and :ABORT NIL.
329 Invoking the initial ABORT restart established by MAKE-THREAD is
330 equivalent to calling ABORT-THREAD in other than main threads.
331 However, whereas ABORT restart may be rebound, ABORT-THREAD always
332 unwinds the entire thread. (Behaviour of the initial ABORT restart for
333 main thread depends on the :TOPLEVEL argument to
334 SB-EXT:SAVE-LISP-AND-DIE.)
336 See also: RETURN-FROM-THREAD and SB-EXT:EXIT."
337 (let ((self *current-thread*))
338 (cond ((main-thread-p self)
339 (unless allow-exit
340 (error 'simple-thread-error
341 :format-control "~@<Tried to abort initial thread, but ~
342 exit was not allowed.~:@>"))
343 (sb!ext:exit :code 1))
345 ;; We /could/ use TOPLEVEL-CATCHER or %END-OF-THE-WORLD as well, but
346 ;; this seems tidier. Those to are a bit too overloaded already.
347 (throw '%abort-thread t)))))
350 ;;;; Aliens, low level stuff
352 (define-alien-routine "kill_safely"
353 integer
354 (os-thread #!-alpha unsigned #!+alpha unsigned-int)
355 (signal int))
357 (define-alien-routine "wake_thread"
358 integer
359 (os-thread unsigned))
361 #!+sb-thread
362 (progn
363 ;; FIXME it would be good to define what a thread id is or isn't
364 ;; (our current assumption is that it's a fixnum). It so happens
365 ;; that on Linux it's a pid, but it might not be on posix thread
366 ;; implementations.
367 (define-alien-routine ("create_thread" %create-thread)
368 unsigned (lisp-fun-address unsigned))
370 (declaim (inline %block-deferrable-signals))
371 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
372 void
373 (where unsigned)
374 (old unsigned))
376 (defun block-deferrable-signals ()
377 (%block-deferrable-signals 0 0))
379 #!+sb-futex
380 (progn
381 (declaim (inline futex-wait %futex-wait futex-wake))
383 (define-alien-routine ("futex_wait" %futex-wait) int
384 (word unsigned) (old-value unsigned)
385 (to-sec long) (to-usec unsigned-long))
387 (defun futex-wait (word old to-sec to-usec)
388 (with-interrupts
389 (%futex-wait word old to-sec to-usec)))
391 (define-alien-routine "futex_wake"
392 int (word unsigned) (n unsigned-long))))
394 ;;; used by debug-int.lisp to access interrupt contexts
396 ;;; The two uses immediately below of (unsigned-byte 27) are arbitrary,
397 ;;; as a more reasonable type restriction is an integer from 0 to
398 ;;; (+ (primitive-object-size
399 ;;; (find 'thread *primitive-objects* :key #'primitive-object-name))
400 ;;; MAX-INTERRUPTS) ; defined only for C in 'interrupt.h'
402 ;;; The x86 32-bit port is helped slightly by having a stricter constraint
403 ;;; than the (unsigned-byte 32) from its DEFKNOWN of this function.
404 ;;; Ideally a single defknown would work for any backend because the thread
405 ;;; structure is, after all, defined in the generic objdefs. But the VM needs
406 ;;; the defknown before the VOP, and this file comes too late, so we'd
407 ;;; need to pick some other place - maybe 'thread.lisp'?
409 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
410 #!-sb-thread
411 (defun sb!vm::current-thread-offset-sap (n)
412 (declare (type (unsigned-byte 27) n))
413 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
414 (* n sb!vm:n-word-bytes)))
416 #!+sb-thread
417 (defun sb!vm::current-thread-offset-sap (n)
418 (declare (type (unsigned-byte 27) n))
419 (sb!vm::current-thread-offset-sap n))
422 (defmacro with-deadlocks ((thread lock &optional (timeout nil timeoutp)) &body forms)
423 (with-unique-names (n-thread n-lock new n-timeout)
424 `(let* ((,n-thread ,thread)
425 (,n-lock ,lock)
426 (,n-timeout ,(when timeoutp
427 `(or ,timeout
428 (when sb!impl::*deadline*
429 sb!impl::*deadline-seconds*))))
430 (,new (if ,n-timeout
431 ;; Using CONS tells the rest of the system there's a
432 ;; timeout in place, so it isn't considered a deadlock.
433 (cons ,n-timeout ,n-lock)
434 ,n-lock)))
435 (declare (dynamic-extent ,new))
436 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
437 ;; in places where interrupts should already be disabled.
438 (unwind-protect
439 (progn
440 (setf (thread-waiting-for ,n-thread) ,new)
441 (barrier (:write))
442 ,@forms)
443 ;; Interrupt handlers and GC save and restore any
444 ;; previous wait marks using WITHOUT-DEADLOCKS below.
445 (setf (thread-waiting-for ,n-thread) nil)
446 (barrier (:write))))))
448 ;;;; Mutexes
450 #!+sb-doc
451 (setf (fdocumentation 'make-mutex 'function)
452 "Create a mutex."
453 (fdocumentation 'mutex-name 'function)
454 "The name of the mutex. Setfable.")
456 #!+(and sb-thread sb-futex)
457 (progn
458 (define-structure-slot-addressor mutex-state-address
459 :structure mutex
460 :slot state)
461 ;; Important: current code assumes these are fixnums or other
462 ;; lisp objects that don't need pinning.
463 (defconstant +lock-free+ 0)
464 (defconstant +lock-taken+ 1)
465 (defconstant +lock-contested+ 2))
467 (defun mutex-owner (mutex)
468 #!+sb-doc
469 "Current owner of the mutex, NIL if the mutex is free. Naturally,
470 this is racy by design (another thread may acquire the mutex after
471 this function returns), it is intended for informative purposes. For
472 testing whether the current thread is holding a mutex see
473 HOLDING-MUTEX-P."
474 ;; Make sure to get the current value.
475 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
477 (sb!ext:defglobal **deadlock-lock** nil)
479 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
480 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
481 (defun check-deadlock ()
482 (let* ((self *current-thread*)
483 (origin (progn
484 (barrier (:read))
485 (thread-waiting-for self))))
486 (labels ((detect-deadlock (lock)
487 (let ((other-thread (mutex-%owner lock)))
488 (cond ((not other-thread))
489 ((eq self other-thread)
490 (let ((chain
491 (with-cas-lock ((symbol-value '**deadlock-lock**))
492 (prog1 (deadlock-chain self origin)
493 ;; We're now committed to signaling the
494 ;; error and breaking the deadlock, so
495 ;; mark us as no longer waiting on the
496 ;; lock. This ensures that a single
497 ;; deadlock is reported in only one
498 ;; thread, and that we don't look like
499 ;; we're waiting on the lock when print
500 ;; stuff -- because that may lead to
501 ;; further deadlock checking, in turn
502 ;; possibly leading to a bogus vicious
503 ;; metacycle on PRINT-OBJECT.
504 (setf (thread-waiting-for self) nil)))))
505 (error 'thread-deadlock
506 :thread *current-thread*
507 :cycle chain)))
509 (let ((other-lock (progn
510 (barrier (:read))
511 (thread-waiting-for other-thread))))
512 ;; If the thread is waiting with a timeout OTHER-LOCK
513 ;; is a cons, and we don't consider it a deadlock -- since
514 ;; it will time out on its own sooner or later.
515 (when (mutex-p other-lock)
516 (detect-deadlock other-lock)))))))
517 (deadlock-chain (thread lock)
518 (let* ((other-thread (mutex-owner lock))
519 (other-lock (when other-thread
520 (barrier (:read))
521 (thread-waiting-for other-thread))))
522 (cond ((not other-thread)
523 ;; The deadlock is gone -- maybe someone unwound
524 ;; from the same deadlock already?
525 (return-from check-deadlock nil))
526 ((consp other-lock)
527 ;; There's a timeout -- no deadlock.
528 (return-from check-deadlock nil))
529 ((waitqueue-p other-lock)
530 ;; Not a lock.
531 (return-from check-deadlock nil))
532 ((eq self other-thread)
533 ;; Done
534 (list (list thread lock)))
536 (if other-lock
537 (cons (cons thread lock)
538 (deadlock-chain other-thread other-lock))
539 ;; Again, the deadlock is gone?
540 (return-from check-deadlock nil)))))))
541 ;; Timeout means there is no deadlock
542 (when (mutex-p origin)
543 (detect-deadlock origin)
544 t))))
546 (defun %try-mutex (mutex new-owner)
547 (declare (type mutex mutex) (optimize (speed 3)))
548 (barrier (:read))
549 (let ((old (mutex-%owner mutex)))
550 (when (eq new-owner old)
551 (error "Recursive lock attempt ~S." mutex))
552 #!-sb-thread
553 (when old
554 (error "Strange deadlock on ~S in an unithreaded build?" mutex))
555 #!-(and sb-thread sb-futex)
556 (and (not old)
557 ;; Don't even bother to try to CAS if it looks bad.
558 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
559 #!+(and sb-thread sb-futex)
560 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
561 (when (eql +lock-free+ (sb!ext:compare-and-swap (mutex-state mutex)
562 +lock-free+
563 +lock-taken+))
564 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
565 (when prev
566 (bug "Old owner in free mutex: ~S" prev))
567 t))))
569 #!+sb-thread
570 (defun %%wait-for-mutex (mutex new-owner to-sec to-usec stop-sec stop-usec)
571 (declare (type mutex mutex) (optimize (speed 3)))
572 #!-sb-futex
573 (declare (ignore to-sec to-usec))
574 #!-sb-futex
575 (flet ((cas ()
576 (loop repeat 100
577 when (and (progn
578 (barrier (:read))
579 (not (mutex-%owner mutex)))
580 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil
581 new-owner)))
582 do (return-from cas t)
583 else
585 (sb!ext:spin-loop-hint))
586 ;; Check for pending interrupts.
587 (with-interrupts nil)))
588 (declare (dynamic-extent #'cas))
589 (sb!impl::%%wait-for #'cas stop-sec stop-usec))
590 #!+sb-futex
591 ;; This is a fairly direct translation of the Mutex 2 algorithm from
592 ;; "Futexes are Tricky" by Ulrich Drepper.
593 (flet ((maybe (old)
594 (when (eql +lock-free+ old)
595 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
596 nil new-owner)))
597 (when prev
598 (bug "Old owner in free mutex: ~S" prev))
599 (return-from %%wait-for-mutex t)))))
600 (prog ((old (sb!ext:compare-and-swap (mutex-state mutex)
601 +lock-free+ +lock-taken+)))
602 ;; Got it right off the bat?
603 (maybe old)
604 :retry
605 ;; Mark it as contested, and sleep. (Exception: it was just released.)
606 (when (or (eql +lock-contested+ old)
607 (not (eql +lock-free+
608 (sb!ext:compare-and-swap
609 (mutex-state mutex) +lock-taken+ +lock-contested+))))
610 (when (eql 1 (with-pinned-objects (mutex)
611 (futex-wait (mutex-state-address mutex)
612 (get-lisp-obj-address +lock-contested+)
613 (or to-sec -1)
614 (or to-usec 0))))
615 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
616 ;; 0 = normal wakeup
617 ;; 1 = ETIMEDOUT ***DONE***
618 ;; 2 = EINTR, a spurious wakeup
619 (return-from %%wait-for-mutex nil)))
620 ;; Try to get it, still marking it as contested.
621 (maybe
622 (sb!ext:compare-and-swap (mutex-state mutex) +lock-free+ +lock-contested+))
623 ;; Update timeout if necessary.
624 (when stop-sec
625 (setf (values to-sec to-usec)
626 (sb!impl::relative-decoded-times stop-sec stop-usec)))
627 ;; Spin.
628 (go :retry))))
630 #!+sb-thread
631 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
632 (with-deadlocks (self mutex timeout)
633 (with-interrupts (check-deadlock))
634 (tagbody
635 :again
636 (return-from %wait-for-mutex
637 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
638 (when deadlinep
639 (signal-deadline)
640 ;; FIXME: substract elapsed time from timeout...
641 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
642 (decode-timeout timeout))
643 (go :again)))))))
645 (define-deprecated-function :early "1.0.37.33" get-mutex (grab-mutex)
646 (mutex &optional new-owner (waitp t) (timeout nil))
647 (declare (ignorable waitp timeout))
648 (let ((new-owner (or new-owner *current-thread*)))
649 (or (%try-mutex mutex new-owner)
650 #!+sb-thread
651 (when waitp
652 (multiple-value-call #'%wait-for-mutex
653 mutex new-owner timeout (decode-timeout timeout))))))
655 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
656 #!+sb-doc
657 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
658 the mutex is not immediately available, sleep until it is available.
660 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
661 GRAB-MUTEX should try to acquire the lock in the contested case.
663 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
664 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
665 that GRAB-MUTEX did -not- acquire the lock.
667 Notes:
669 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
671 (WITHOUT-INTERRUPTS
673 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
674 ...)
676 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
677 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
678 allows the call to be interrupted from sleep.
680 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
681 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
682 DEADLINE-TIMEOUT if the global deadline was due already on entering
683 GRAB-MUTEX.
685 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
686 future versions.
688 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
689 directly.
691 (declare (ignorable waitp timeout))
692 (let ((self *current-thread*))
693 (or (%try-mutex mutex self)
694 #!+sb-thread
695 (when waitp
696 (multiple-value-call #'%wait-for-mutex
697 mutex self timeout (decode-timeout timeout))))))
699 (defun release-mutex (mutex &key (if-not-owner :punt))
700 #!+sb-doc
701 "Release MUTEX by setting it to NIL. Wake up threads waiting for
702 this mutex.
704 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
705 around calls to it.
707 If the current thread is not the owner of the mutex then it silently
708 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
709 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
710 IF-NOT-OWNER is :FORCE)."
711 (declare (type mutex mutex))
712 ;; Order matters: set owner to NIL before releasing state.
713 (let* ((self *current-thread*)
714 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
715 (unless (eq self old-owner)
716 (ecase if-not-owner
717 ((:punt) (return-from release-mutex nil))
718 ((:warn)
719 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
720 ((:force)))
721 (setf (mutex-%owner mutex) nil)
722 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
723 ;; barrier instead?
724 (barrier (:memory)))
725 #!+(and sb-thread sb-futex)
726 (when old-owner
727 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
728 ;; unsigned-byte type this can be used:
730 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
731 ;; (unless (eql old +lock-free+)
732 ;; (setf (mutex-state mutex) +lock-free+)
733 ;; (with-pinned-objects (mutex)
734 ;; (futex-wake (mutex-state-address mutex) 1))))
735 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
736 +lock-taken+ +lock-free+)))
737 (when (eql old +lock-contested+)
738 (sb!ext:compare-and-swap (mutex-state mutex)
739 +lock-contested+ +lock-free+)
740 (with-pinned-objects (mutex)
741 (futex-wake (mutex-state-address mutex) 1))))
742 nil)))
745 ;;;; Waitqueues/condition variables
747 ;; For possible DX-allocating, see the notinline counterpart after the
748 ;; PROGN below
749 (declaim (inline make-waitqueue))
750 #!+(or (not sb-thread) sb-futex)
751 (defstruct (waitqueue (:constructor make-waitqueue (&key name)))
752 #!+sb-doc
753 "Waitqueue type."
754 (name nil :type (or null thread-name))
755 #!+(and sb-thread sb-futex)
756 (token nil))
758 #!+(and sb-thread (not sb-futex))
759 (progn
760 (defstruct (waitqueue (:constructor make-waitqueue (&key name)))
761 #!+sb-doc
762 "Waitqueue type."
763 (name nil :type (or null thread-name))
764 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
765 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
766 ;; lock. In most cases this should be uncontested thanks to the mutex --
767 ;; the only case where that might not be true is when CONDITION-WAIT
768 ;; unwinds and %WAITQUEUE-DROP is called.
769 %owner
770 %head
771 %tail)
773 (defun %waitqueue-enqueue (thread queue)
774 (setf (thread-waiting-for thread) queue)
775 (let ((head (waitqueue-%head queue))
776 (tail (waitqueue-%tail queue))
777 (new (list thread)))
778 (unless head
779 (setf (waitqueue-%head queue) new))
780 (when tail
781 (setf (cdr tail) new))
782 (setf (waitqueue-%tail queue) new)
783 nil))
784 (defun %waitqueue-drop (thread queue)
785 (setf (thread-waiting-for thread) nil)
786 (let ((head (waitqueue-%head queue)))
787 (do ((list head (cdr list))
788 (prev nil list))
789 ((or (null list)
790 (eq (car list) thread))
791 (when list
792 (let ((rest (cdr list)))
793 (cond (prev
794 (setf (cdr prev) rest))
796 (setf (waitqueue-%head queue) rest
797 prev rest)))
798 (unless rest
799 (setf (waitqueue-%tail queue) prev)))))))
800 nil)
801 (defun %waitqueue-wakeup (queue n)
802 (declare (fixnum n))
803 (loop while (plusp n)
804 for next = (let ((head (waitqueue-%head queue))
805 (tail (waitqueue-%tail queue)))
806 (when head
807 (if (eq head tail)
808 (setf (waitqueue-%head queue) nil
809 (waitqueue-%tail queue) nil)
810 (setf (waitqueue-%head queue) (cdr head)))
811 (car head)))
812 while next
813 do (when (eq queue (sb!ext:compare-and-swap
814 (thread-waiting-for next) queue nil))
815 (decf n)))
816 nil))
817 (declaim (notinline make-waitqueue))
819 (def!method print-object ((waitqueue waitqueue) stream)
820 (print-unreadable-object (waitqueue stream :type t :identity t)
821 (format stream "~@[~A~]" (waitqueue-name waitqueue))))
823 #!+sb-doc
824 (setf (fdocumentation 'waitqueue-name 'function)
825 "The name of the waitqueue. Setfable."
826 (fdocumentation 'make-waitqueue 'function)
827 "Create a waitqueue.")
829 #!+(and sb-thread sb-futex)
830 (define-structure-slot-addressor waitqueue-token-address
831 :structure waitqueue
832 :slot token)
834 (defun condition-wait (queue mutex &key timeout)
835 #!+sb-doc
836 "Atomically release MUTEX and start waiting on QUEUE for till another thread
837 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
838 queue, at which point we re-acquire MUTEX and return T.
840 Spurious wakeups are possible.
842 If TIMEOUT is given, it is the maximum number of seconds to wait, including
843 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
844 wakeup and re-acquisition do not occur within the given time, returns NIL
845 without re-acquiring the mutex.
847 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
849 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
850 occurred the correct way to write code that uses CONDITION-WAIT is to loop
851 around the call, checking the the associated data:
853 (defvar *data* nil)
854 (defvar *queue* (make-waitqueue))
855 (defvar *lock* (make-mutex))
857 ;; Consumer
858 (defun pop-data (&optional timeout)
859 (with-mutex (*lock*)
860 (loop until *data*
861 do (or (condition-wait *queue* *lock* :timeout timeout)
862 ;; Lock not held, must unwind without touching *data*.
863 (return-from pop-data nil)))
864 (pop *data*)))
866 ;; Producer
867 (defun push-data (data)
868 (with-mutex (*lock*)
869 (push data *data*)
870 (condition-notify *queue*)))
872 #!-sb-thread
873 (declare (ignore queue))
874 (assert mutex)
875 #!-sb-thread
876 (sb!ext:wait-for nil :timeout timeout) ; Yeah...
877 #!+sb-thread
878 (let ((me *current-thread*))
879 (barrier (:read))
880 (assert (eq me (mutex-%owner mutex)))
881 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
882 (decode-timeout timeout)
883 (let ((status :interrupted))
884 ;; Need to disable interrupts so that we don't miss grabbing the
885 ;; mutex on our way out.
886 (without-interrupts
887 (unwind-protect
888 (progn
889 #!-sb-futex
890 (progn
891 (%with-cas-lock ((waitqueue-%owner queue))
892 (%waitqueue-enqueue me queue))
893 (release-mutex mutex)
894 (setf status
895 (or (flet ((wakeup ()
896 (barrier (:read))
897 (unless (eq queue (thread-waiting-for me))
898 :ok)))
899 (declare (dynamic-extent #'wakeup))
900 (allow-with-interrupts
901 (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
902 :timeout)))
903 #!+sb-futex
904 (with-pinned-objects (queue me)
905 (setf (waitqueue-token queue) me)
906 (release-mutex mutex)
907 ;; Now we go to sleep using futex-wait. If anyone else
908 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
909 ;; this comment, it will change the token, and so futex-wait
910 ;; returns immediately instead of sleeping. Ergo, no lost
911 ;; wakeup. We may get spurious wakeups, but that's ok.
912 (setf status
913 (case (allow-with-interrupts
914 (futex-wait (waitqueue-token-address queue)
915 (get-lisp-obj-address me)
916 ;; our way of saying "no
917 ;; timeout":
918 (or to-sec -1)
919 (or to-usec 0)))
920 ((1)
921 ;; 1 = ETIMEDOUT
922 :timeout)
924 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
925 ;; 0 = normal wakeup
926 ;; 2 = EINTR, a spurious wakeup
927 :ok)))))
928 #!-sb-futex
929 (%with-cas-lock ((waitqueue-%owner queue))
930 (if (eq queue (thread-waiting-for me))
931 (%waitqueue-drop me queue)
932 (unless (eq :ok status)
933 ;; CONDITION-NOTIFY thinks we've been woken up, but really
934 ;; we're unwinding. Wake someone else up.
935 (%waitqueue-wakeup queue 1))))
936 ;; Update timeout for mutex re-aquisition.
937 (when (and (eq :ok status) to-sec)
938 (setf (values to-sec to-usec)
939 (sb!impl::relative-decoded-times stop-sec stop-usec)))
940 ;; If we ran into deadline, try to get the mutex before
941 ;; signaling. If we don't unwind it will look like a normal
942 ;; return from user perspective.
943 (when (and (eq :timeout status) deadlinep)
944 (let ((got-it (%try-mutex mutex me)))
945 (allow-with-interrupts
946 (signal-deadline)
947 (cond (got-it
948 (return-from condition-wait t))
950 ;; The deadline may have changed.
951 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
952 (decode-timeout timeout))
953 (setf status :ok))))))
954 ;; Re-acquire the mutex for normal return.
955 (when (eq :ok status)
956 (unless (or (%try-mutex mutex me)
957 (allow-with-interrupts
958 (%wait-for-mutex mutex me timeout
959 to-sec to-usec
960 stop-sec stop-usec deadlinep)))
961 (setf status :timeout)))))
962 (or (eq :ok status)
963 (unless (eq :timeout status)
964 ;; The only case we return normally without re-acquiring the
965 ;; mutex is when there is a :TIMEOUT that runs out.
966 (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
968 (defun condition-notify (queue &optional (n 1))
969 #!+sb-doc
970 "Notify N threads waiting on QUEUE.
972 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
973 must be held by this thread during this call."
974 #!-sb-thread
975 (declare (ignore queue n))
976 #!-sb-thread
977 (error "Not supported in unithread builds.")
978 #!+sb-thread
979 (declare (type (and fixnum (integer 1)) n))
980 (/show0 "Entering CONDITION-NOTIFY")
981 #!+sb-thread
982 (progn
983 #!-sb-futex
984 (with-cas-lock ((waitqueue-%owner queue))
985 (%waitqueue-wakeup queue n))
986 #!+sb-futex
987 (progn
988 ;; No problem if >1 thread notifies during the comment in condition-wait:
989 ;; as long as the value in queue-data isn't the waiting thread's id, it
990 ;; matters not what it is -- using the queue object itself is handy.
992 ;; XXX we should do something to ensure that the result of this setf
993 ;; is visible to all CPUs.
995 ;; ^-- surely futex_wake() involves a memory barrier?
996 (setf (waitqueue-token queue) queue)
997 (with-pinned-objects (queue)
998 (futex-wake (waitqueue-token-address queue) n)))))
1000 (defun condition-broadcast (queue)
1001 #!+sb-doc
1002 "Notify all threads waiting on QUEUE.
1004 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
1005 must be held by this thread during this call."
1006 (condition-notify queue
1007 ;; On a 64-bit platform truncating M-P-F to an int
1008 ;; results in -1, which wakes up only one thread.
1009 (ldb (byte 29 0)
1010 most-positive-fixnum)))
1013 ;;;; Semaphores
1015 (declaim (inline make-semaphore)) ;; for possible DX-allocating
1016 (defstruct (semaphore (:constructor make-semaphore
1017 (&key name ((:count %count) 0))))
1018 #!+sb-doc
1019 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
1020 should be considered an implementation detail, and may change in the
1021 future."
1022 (name nil :type (or null thread-name))
1023 (%count 0 :type (integer 0))
1024 (waitcount 0 :type sb!vm:word)
1025 (mutex (make-mutex))
1026 (queue (make-waitqueue)))
1027 (declaim (notinline make-semaphore))
1029 #!+sb-doc
1030 (setf (fdocumentation 'semaphore-name 'function)
1031 "The name of the semaphore INSTANCE. Setfable."
1032 (fdocumentation 'make-semaphore 'function)
1033 "Create a semaphore with the supplied COUNT and NAME.")
1035 (defstruct (semaphore-notification (:constructor make-semaphore-notification ())
1036 (:copier nil))
1037 #!+sb-doc
1038 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
1039 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
1040 multiple threads are using the same notification object in parallel."
1041 (%status nil :type boolean))
1043 #!+sb-doc
1044 (setf (fdocumentation 'make-semaphore-notification 'function)
1045 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
1046 is initially NIL.")
1048 (declaim (inline semaphore-notification-status))
1049 (defun semaphore-notification-status (semaphore-notification)
1050 #!+sb-doc
1051 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
1052 SEMAPHORE-NOTIFICATION has succeeded since the notification object was created
1053 or cleared."
1054 (barrier (:read))
1055 (semaphore-notification-%status semaphore-notification))
1057 (declaim (inline clear-semaphore-notification))
1058 (defun clear-semaphore-notification (semaphore-notification)
1059 #!+sb-doc
1060 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
1061 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
1062 (barrier (:write)
1063 (setf (semaphore-notification-%status semaphore-notification) nil)))
1065 (declaim (inline semaphore-count))
1066 (defun semaphore-count (instance)
1067 #!+sb-doc
1068 "Returns the current count of the semaphore INSTANCE."
1069 (barrier (:read))
1070 (semaphore-%count instance))
1072 (declaim (ftype (sfunction (semaphore (integer 1) (or boolean real)
1073 (or null semaphore-notification) symbol)
1075 %decrement-semaphore))
1076 (defun %decrement-semaphore (semaphore n wait notification context)
1077 (when (and notification (semaphore-notification-status notification))
1078 (with-simple-restart (continue "Clear notification status and continue.")
1079 (error "~@<Semaphore notification object status not cleared on ~
1080 entry to ~S on ~S.~:@>"
1081 context semaphore))
1082 (clear-semaphore-notification notification))
1084 ;; A more direct implementation based directly on futexes should be
1085 ;; possible.
1087 ;; We need to disable interrupts so that we don't forget to
1088 ;; decrement the waitcount (which would happen if an asynch
1089 ;; interrupt should catch us on our way out from the loop.)
1091 ;; FIXME: No timeout on initial mutex acquisition.
1092 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1093 (flet ((success (new-count)
1094 (prog1
1095 (setf (semaphore-%count semaphore) new-count)
1096 (when notification
1097 (setf (semaphore-notification-%status notification) t)))))
1098 ;; Quick check: can we decrement right away? If not, return or
1099 ;; enter the wait loop.
1100 (cond
1101 ((let ((old-count (semaphore-%count semaphore)))
1102 (when (>= old-count n)
1103 (success (- old-count n)))))
1104 ((not wait)
1105 nil)
1107 (unwind-protect
1108 (let (old-count
1109 (timeout (when (realp wait) wait)))
1110 ;; Need to use ATOMIC-INCF despite the lock, because
1111 ;; on our way out from here we might not be locked
1112 ;; anymore -- so another thread might be tweaking this
1113 ;; in parallel using ATOMIC-DECF. No danger over
1114 ;; overflow, since there it at most one increment per
1115 ;; thread waiting on the semaphore.
1116 (sb!ext:atomic-incf (semaphore-waitcount semaphore))
1117 (loop until (>= (setf old-count (semaphore-%count semaphore)) n)
1118 do (or (condition-wait (semaphore-queue semaphore)
1119 (semaphore-mutex semaphore)
1120 :timeout timeout)
1121 (return-from %decrement-semaphore nil)))
1122 (success (- old-count n)))
1123 ;; Need to use ATOMIC-DECF as we may unwind without the
1124 ;; lock being held!
1125 (sb!ext:atomic-decf (semaphore-waitcount semaphore))))))))
1127 (declaim (ftype (sfunction (semaphore &key
1128 (:n (integer 1))
1129 (:timeout (real (0)))
1130 (:notification semaphore-notification))
1131 (or null (integer 0)))
1132 wait-on-semaphore))
1133 (defun wait-on-semaphore (semaphore &key (n 1) timeout notification)
1134 #!+sb-doc
1135 "Decrement the count of SEMAPHORE by N if the count would not be negative.
1137 Else blocks until the semaphore can be decremented. Returns the new count of
1138 SEMAPHORE on success.
1140 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
1141 cannot be decremented in that time, returns NIL without decrementing the
1142 count.
1144 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
1145 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
1146 decrements the count, the status is set to T."
1147 (%decrement-semaphore
1148 semaphore n (or timeout t) notification 'wait-on-semaphore))
1150 (declaim (ftype (sfunction (semaphore &optional
1151 (integer 1) semaphore-notification)
1152 (or null (integer 0)))
1153 try-semaphore))
1154 (defun try-semaphore (semaphore &optional (n 1) notification)
1155 #!+sb-doc
1156 "Try to decrement the count of SEMAPHORE by N. If the count were to
1157 become negative, punt and return NIL, otherwise return the new count of
1158 SEMAPHORE.
1160 If NOTIFICATION is given it must be a semaphore notification object
1161 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1162 the status is set to T."
1163 (%decrement-semaphore semaphore n nil notification 'try-semaphore))
1165 (defun signal-semaphore (semaphore &optional (n 1))
1166 #!+sb-doc
1167 "Increment the count of SEMAPHORE by N. If there are threads waiting
1168 on this semaphore, then N of them is woken up."
1169 (declare (type (integer 1) n))
1170 ;; Need to disable interrupts so that we don't lose a wakeup after
1171 ;; we have incremented the count.
1172 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1173 (let ((waitcount (semaphore-waitcount semaphore))
1174 (count (incf (semaphore-%count semaphore) n)))
1175 (when (plusp waitcount)
1176 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1179 ;;;; Job control, independent listeners
1181 (defstruct session
1182 (lock (make-mutex :name "session lock"))
1183 (threads nil)
1184 (interactive-threads nil)
1185 (interactive-threads-queue (make-waitqueue)))
1187 (defvar *session* nil)
1189 ;;; The debugger itself tries to acquire the session lock, don't let
1190 ;;; funny situations (like getting a sigint while holding the session
1191 ;;; lock) occur. At the same time we need to allow interrupts while
1192 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1193 ;;; be interruptible.
1195 ;;; Take care: we sometimes need to obtain the session lock while
1196 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1197 ;;; _after_ getting a session lock! (Deadlock risk.)
1199 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1200 ;;; like the above.
1201 (defmacro with-session-lock ((session) &body body)
1202 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1203 ,@body))
1205 (defun new-session ()
1206 (make-session :threads (list *current-thread*)
1207 :interactive-threads (list *current-thread*)))
1209 (defun init-job-control ()
1210 (/show0 "Entering INIT-JOB-CONTROL")
1211 (setf *session* (new-session))
1212 (/show0 "Exiting INIT-JOB-CONTROL"))
1214 (defun %delete-thread-from-session (thread session)
1215 (with-session-lock (session)
1216 (setf (session-threads session)
1217 ;; DELQ never conses, but DELETE does. (FIXME)
1218 (delq thread (session-threads session))
1219 (session-interactive-threads session)
1220 (delq thread (session-interactive-threads session)))))
1222 (defun call-with-new-session (fn)
1223 (%delete-thread-from-session *current-thread* *session*)
1224 (let ((*session* (new-session)))
1225 (funcall fn)))
1227 (defmacro with-new-session (args &body forms)
1228 (declare (ignore args)) ;for extensibility
1229 (sb!int:with-unique-names (fb-name)
1230 `(labels ((,fb-name () ,@forms))
1231 (call-with-new-session (function ,fb-name)))))
1233 ;;; Remove thread from its session, if it has one.
1234 #!+sb-thread
1235 (defun handle-thread-exit (thread)
1236 (/show0 "HANDLING THREAD EXIT")
1237 (when *exit-in-process*
1238 (%exit))
1239 ;; Lisp-side cleanup
1240 (with-all-threads-lock
1241 (setf (thread-%alive-p thread) nil)
1242 (setf (thread-os-thread thread) 0)
1243 (setq *all-threads* (delq thread *all-threads*))
1244 (when *session*
1245 (%delete-thread-from-session thread *session*))))
1247 (defun %exit-other-threads ()
1248 ;; Grabbing this lock prevents new threads from
1249 ;; being spawned, and guarantees that *ALL-THREADS*
1250 ;; is up to date.
1251 (with-deadline (:seconds nil :override t)
1252 (grab-mutex *make-thread-lock*)
1253 (let ((timeout sb!ext:*exit-timeout*)
1254 (code *exit-in-process*)
1255 (current *current-thread*)
1256 (joinees nil)
1257 (main nil))
1258 (dolist (thread (list-all-threads))
1259 (cond ((eq thread current))
1260 ((main-thread-p thread)
1261 (setf main thread))
1263 (handler-case
1264 (progn
1265 (terminate-thread thread)
1266 (push thread joinees))
1267 (interrupt-thread-error ())))))
1268 (with-progressive-timeout (time-left :seconds timeout)
1269 (dolist (thread joinees)
1270 (join-thread thread :default t :timeout (time-left)))
1271 ;; Need to defer till others have joined, because when main
1272 ;; thread exits, we're gone. Can't use TERMINATE-THREAD -- would
1273 ;; get the exit code wrong.
1274 (when main
1275 (handler-case
1276 (interrupt-thread
1277 main
1278 (lambda ()
1279 (setf *exit-in-process* (list code))
1280 (throw 'sb!impl::%end-of-the-world t)))
1281 (interrupt-thread-error ()))
1282 ;; Normally this never finishes, as once the main-thread unwinds we
1283 ;; exit with the right code, but if times out before that happens,
1284 ;; we will exit after returning -- or rathe racing the main thread
1285 ;; to calling OS-EXIT.
1286 (join-thread main :default t :timeout (time-left)))))))
1288 (defun terminate-session ()
1289 #!+sb-doc
1290 "Kill all threads in session except for this one. Does nothing if current
1291 thread is not the foreground thread."
1292 ;; FIXME: threads created in other threads may escape termination
1293 (let ((to-kill
1294 (with-session-lock (*session*)
1295 (and (eq *current-thread*
1296 (car (session-interactive-threads *session*)))
1297 (session-threads *session*)))))
1298 ;; do the kill after dropping the mutex; unwind forms in dying
1299 ;; threads may want to do session things
1300 (dolist (thread to-kill)
1301 (unless (eq thread *current-thread*)
1302 ;; terminate the thread but don't be surprised if it has
1303 ;; exited in the meantime
1304 (handler-case (terminate-thread thread)
1305 (interrupt-thread-error ()))))))
1307 ;;; called from top of invoke-debugger
1308 (defun debugger-wait-until-foreground-thread (stream)
1309 #!+sb-doc
1310 "Returns T if thread had been running in background, NIL if it was
1311 interactive."
1312 (declare (ignore stream))
1313 #!-sb-thread nil
1314 #!+sb-thread
1315 (prog1
1316 (with-session-lock (*session*)
1317 (not (member *current-thread*
1318 (session-interactive-threads *session*))))
1319 (get-foreground)))
1321 (defun get-foreground ()
1322 #!-sb-thread t
1323 #!+sb-thread
1324 (let ((was-foreground t))
1325 (loop
1326 (/show0 "Looping in GET-FOREGROUND")
1327 (with-session-lock (*session*)
1328 (let ((int-t (session-interactive-threads *session*)))
1329 (when (eq (car int-t) *current-thread*)
1330 (unless was-foreground
1331 (format *query-io* "Resuming thread ~A~%" *current-thread*))
1332 (return-from get-foreground t))
1333 (setf was-foreground nil)
1334 (unless (member *current-thread* int-t)
1335 (setf (cdr (last int-t))
1336 (list *current-thread*)))
1337 (condition-wait
1338 (session-interactive-threads-queue *session*)
1339 (session-lock *session*)))))))
1341 (defun release-foreground (&optional next)
1342 #!+sb-doc
1343 "Background this thread. If NEXT is supplied, arrange for it to
1344 have the foreground next."
1345 #!-sb-thread (declare (ignore next))
1346 #!-sb-thread nil
1347 #!+sb-thread
1348 (with-session-lock (*session*)
1349 (when (rest (session-interactive-threads *session*))
1350 (setf (session-interactive-threads *session*)
1351 (delete *current-thread* (session-interactive-threads *session*))))
1352 (when next
1353 (setf (session-interactive-threads *session*)
1354 (list* next
1355 (delete next (session-interactive-threads *session*)))))
1356 (condition-broadcast (session-interactive-threads-queue *session*))))
1358 (defun interactive-threads (&optional (session *session*))
1359 #!+sb-doc
1360 "Return the interactive threads of SESSION defaulting to the current
1361 session."
1362 (session-interactive-threads session))
1364 (defun foreground-thread (&optional (session *session*))
1365 #!+sb-doc
1366 "Return the foreground thread of SESSION defaulting to the current
1367 session."
1368 (first (interactive-threads session)))
1370 (defun make-listener-thread (tty-name)
1371 (assert (probe-file tty-name))
1372 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1373 (out (sb!unix:unix-dup in))
1374 (err (sb!unix:unix-dup in)))
1375 (labels ((thread-repl ()
1376 (sb!unix::unix-setsid)
1377 (let* ((sb!impl::*stdin*
1378 (make-fd-stream in :input t :buffering :line
1379 :dual-channel-p t))
1380 (sb!impl::*stdout*
1381 (make-fd-stream out :output t :buffering :line
1382 :dual-channel-p t))
1383 (sb!impl::*stderr*
1384 (make-fd-stream err :output t :buffering :line
1385 :dual-channel-p t))
1386 (sb!impl::*tty*
1387 (make-fd-stream err :input t :output t
1388 :buffering :line
1389 :dual-channel-p t))
1390 (sb!impl::*descriptor-handlers* nil))
1391 (with-new-session ()
1392 (unwind-protect
1393 (sb!impl::toplevel-repl nil)
1394 (sb!int:flush-standard-output-streams))))))
1395 (make-thread #'thread-repl))))
1398 ;;;; The beef
1400 #!+sb-thread
1401 (defun initial-thread-function-trampoline
1402 (thread setup-sem real-function thread-list arguments arg1 arg2 arg3)
1403 ;; In time we'll move some of the binding presently done in C here
1404 ;; too.
1406 ;; KLUDGE: Here we have a magic list of variables that are not
1407 ;; thread-safe for one reason or another. As people report problems
1408 ;; with the thread safety of certain variables, (e.g. "*print-case* in
1409 ;; multiple threads broken", sbcl-devel 2006-07-14), we add a few more
1410 ;; bindings here. The Right Thing is probably some variant of
1411 ;; Allegro's *cl-default-special-bindings*, as that is at least
1412 ;; accessible to users to secure their own libraries.
1413 ;; --njf, 2006-07-15
1415 ;; As it is, this lambda must not cons until we are ready to run
1416 ;; GC. Be very careful.
1417 (let* ((*current-thread* thread)
1418 (*restart-clusters* nil)
1419 (*handler-clusters* sb!kernel::**initial-handler-clusters**)
1420 (*exit-in-process* nil)
1421 (sb!impl::*deadline* nil)
1422 (sb!impl::*deadline-seconds* nil)
1423 (sb!impl::*step-out* nil)
1424 ;; internal reader variables
1425 (sb!impl::*token-buf-pool* nil)
1426 ;; internal printer variables
1427 (sb!impl::*previous-case* nil)
1428 (sb!impl::*previous-readtable-case* nil)
1429 (sb!impl::*internal-symbol-output-fun* #'error)
1430 (sb!impl::*descriptor-handlers* nil)) ; serve-event
1431 (declare (inline make-restart)) ;; to allow DX-allocation
1432 ;; Binding from C
1433 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1434 (setf (thread-os-thread thread) (current-thread-os-thread))
1435 (with-mutex ((thread-result-lock thread))
1436 ;; Normally the list is allocated in the parent thread to
1437 ;; avoid consing in a nascent thread.
1439 (let* ((thread-list (or thread-list
1440 (list thread thread)))
1441 (session-cons (cdr thread-list)))
1442 (with-all-threads-lock
1443 (setf (cdr thread-list) *all-threads*
1444 *all-threads* thread-list))
1445 (let ((session *session*))
1446 (with-session-lock (session)
1447 (setf (cdr session-cons) (session-threads session)
1448 (session-threads session) session-cons))))
1449 (setf (thread-%alive-p thread) t)
1451 (when setup-sem
1452 (signal-semaphore setup-sem)
1453 ;; setup-sem was dx-allocated, set it to NIL so that the
1454 ;; backtrace doesn't get confused
1455 (setf setup-sem nil))
1457 ;; Using handling-end-of-the-world would be a bit tricky
1458 ;; due to other catches and interrupts, so we essentially
1459 ;; re-implement it here. Once and only once more.
1460 (catch 'sb!impl::toplevel-catcher
1461 (catch 'sb!impl::%end-of-the-world
1462 (catch '%abort-thread
1463 (restart-bind ((abort
1464 (lambda ()
1465 (throw '%abort-thread nil))
1466 :report-function
1467 (lambda (stream)
1468 (format stream "~@<abort thread (~a)~@:>"
1469 *current-thread*))))
1470 (without-interrupts
1471 (unwind-protect
1472 (with-local-interrupts
1473 (setf *gc-inhibit* nil) ;for foreign callbacks
1474 (sb!unix::unblock-deferrable-signals)
1475 (setf (thread-result thread)
1476 (prog1
1477 (multiple-value-list
1478 (unwind-protect
1479 (catch '%return-from-thread
1480 (if (listp arguments)
1481 (apply real-function arguments)
1482 (funcall real-function arg1 arg2 arg3)))
1483 (when *exit-in-process*
1484 (sb!impl::call-exit-hooks))))
1485 #!+sb-safepoint
1486 (sb!kernel::gc-safepoint))))
1487 ;; we're going down, can't handle interrupts
1488 ;; sanely anymore. gc remains enabled.
1489 (block-deferrable-signals)
1490 ;; we don't want to run interrupts in a dead
1491 ;; thread when we leave without-interrupts.
1492 ;; this potentially causes important
1493 ;; interupts to be lost: sigint comes to
1494 ;; mind.
1495 (setq *interrupt-pending* nil)
1496 #!+sb-thruption
1497 (setq *thruption-pending* nil)
1498 (handle-thread-exit thread)))))))))
1499 (values))
1501 (defun make-thread (function &key name arguments ephemeral)
1502 #!+sb-doc
1503 "Create a new thread of NAME that runs FUNCTION with the argument
1504 list designator provided (defaults to no argument). Thread exits when
1505 the function returns. The return values of FUNCTION are kept around
1506 and can be retrieved by JOIN-THREAD.
1508 Invoking the initial ABORT restart established by MAKE-THREAD
1509 terminates the thread.
1511 See also: RETURN-FROM-THREAD, ABORT-THREAD."
1512 #!-sb-thread (declare (ignore function name arguments ephemeral))
1513 #!-sb-thread (error "Not supported in unithread builds.")
1514 #!+sb-thread (assert (or (atom arguments)
1515 (null (cdr (last arguments))))
1516 (arguments)
1517 "Argument passed to ~S, ~S, is an improper list."
1518 'make-thread arguments)
1519 #!+sb-thread
1520 (let ((thread (%make-thread :name name :%ephemeral-p ephemeral)))
1521 (declare (inline make-semaphore
1522 make-waitqueue
1523 make-mutex))
1524 (let* ((setup-sem (make-semaphore :name "Thread setup semaphore"))
1525 (real-function (coerce function 'function))
1526 (arguments (ensure-list arguments))
1527 #!+win32
1528 (fp-modes (dpb 0 sb!vm::float-sticky-bits ;; clear accrued bits
1529 (sb!vm:floating-point-modes)))
1530 ;; Allocate in the parent
1531 (thread-list (list thread thread)))
1532 (declare (dynamic-extent setup-sem))
1533 ;; It could be just pinned instead, but implementing DX closures
1534 ;; is much easier than implementing threading.
1535 #!-(or stack-allocatable-closures stack-allocatable-fixed-objects)
1536 #.(error "Stack allocatable closures required.")
1537 (dx-flet ((initial-thread-function ()
1538 ;; Win32 doesn't inherit parent thread's FP modes,
1539 ;; while it seems to happen everywhere else
1540 #!+win32
1541 (setf (sb!vm:floating-point-modes) fp-modes)
1542 ;; As it is, this lambda must not cons until we are
1543 ;; ready to run GC. Be very careful.
1544 (initial-thread-function-trampoline
1545 thread setup-sem real-function thread-list
1546 arguments nil nil nil)))
1547 ;; If the starting thread is stopped for gc before it signals
1548 ;; the semaphore then we'd be stuck.
1549 (assert (not *gc-inhibit*))
1550 ;; Keep INITIAL-FUNCTION in the dynamic extent until the child
1551 ;; thread is initialized properly. Wrap the whole thing in
1552 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to
1553 ;; another thread.
1554 (with-system-mutex (*make-thread-lock*)
1555 (if (zerop
1556 (%create-thread (get-lisp-obj-address #'initial-thread-function)))
1557 (setf thread nil)
1558 (wait-on-semaphore setup-sem)))))
1559 (or thread (error "Could not create a new thread."))))
1561 (defun join-thread (thread &key (default nil defaultp) timeout)
1562 #!+sb-doc
1563 "Suspend current thread until THREAD exits. Return the result values
1564 of the thread function.
1566 If the thread does not exit within TIMEOUT seconds and DEFAULT is
1567 supplied, return two values: 1) DEFAULT 2) :TIMEOUT. If DEFAULT is not
1568 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-ERROR-PROBLEM
1569 equal to :TIMEOUT.
1571 If the thread did not exit normally (i.e. aborted) and DEFAULT is
1572 supplied, return two values: 1) DEFAULT 2) :ABORT. If DEFAULT is not
1573 supplied, signal a JOIN-THREAD-THREAD-ERROR with problem equal
1574 to :ABORT.
1576 Trying to join the main thread will cause JOIN-THREAD to block until
1577 TIMEOUT occurs or the process exits: when main thread exits, the
1578 entire process exits.
1580 NOTE: Return convention in case of a timeout is experimental and
1581 subject to change."
1582 (let ((lock (thread-result-lock thread))
1583 (got-it nil)
1584 (problem :timeout))
1585 (without-interrupts
1586 (unwind-protect
1587 (cond
1588 ((not (setf got-it
1589 (allow-with-interrupts
1590 ;; Don't use the timeout if the thread is
1591 ;; not alive anymore.
1592 (grab-mutex lock :timeout (and (thread-alive-p thread)
1593 timeout))))))
1594 ((listp (thread-result thread))
1595 (return-from join-thread
1596 (values-list (thread-result thread))))
1598 (setf problem :abort)))
1599 (when got-it
1600 (release-mutex lock))))
1601 (if defaultp
1602 (values default problem)
1603 (error 'join-thread-error :thread thread :problem problem))))
1605 (defun destroy-thread (thread)
1606 (terminate-thread thread))
1608 #-sb-xc-host
1609 (declaim (sb!ext:deprecated
1610 :late ("SBCL" "1.2.15")
1611 (function destroy-thread :replacement terminate-thread)))
1613 #!+sb-thread
1614 (defun enter-foreign-callback (arg1 arg2 arg3)
1615 (initial-thread-function-trampoline
1616 (make-foreign-thread :name "foreign callback")
1617 nil #'sb!alien::enter-alien-callback nil t arg1 arg2 arg3))
1619 (defmacro with-interruptions-lock ((thread) &body body)
1620 `(with-system-mutex ((thread-interruptions-lock ,thread))
1621 ,@body))
1623 ;;; Called from the signal handler.
1624 #!-(or sb-thruption win32)
1625 (defun run-interruption ()
1626 (let ((interruption (with-interruptions-lock (*current-thread*)
1627 (pop (thread-interruptions *current-thread*)))))
1628 ;; If there is more to do, then resignal and let the normal
1629 ;; interrupt deferral mechanism take care of the rest. From the
1630 ;; OS's point of view the signal we are in the handler for is no
1631 ;; longer pending, so the signal will not be lost.
1632 (when (thread-interruptions *current-thread*)
1633 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1634 (when interruption
1635 (funcall interruption))))
1637 #!+sb-thruption
1638 (defun run-interruption ()
1639 (in-interruption () ;the non-thruption code does this in the signal handler
1640 (let ((interruption (with-interruptions-lock (*current-thread*)
1641 (pop (thread-interruptions *current-thread*)))))
1642 (when interruption
1643 (funcall interruption)
1644 ;; I tried implementing this function as an explicit LOOP, because
1645 ;; if we are currently processing the thruption queue, why not do
1646 ;; all of them in one go instead of one-by-one?
1648 ;; I still think LOOPing would be basically the right thing
1649 ;; here. But suppose some interruption unblocked deferrables.
1650 ;; Will the next one be happy with that? The answer is "no", at
1651 ;; least in the sense that there are tests which check that
1652 ;; deferrables are blocked at the beginning of a thruption, and
1653 ;; races that make those tests fail. Whether the tests are
1654 ;; misguided or not, it seems easier/cleaner to loop implicitly
1655 ;; -- and it's also what AK had implemented in the first place.
1657 ;; The implicit loop is achieved by returning to C, but having C
1658 ;; call back to us immediately. The runtime will reset the sigmask
1659 ;; in the mean time.
1660 ;; -- DFL
1661 (setf *thruption-pending* t)))))
1663 (defun interrupt-thread (thread function)
1664 #!+sb-doc
1665 "Interrupt THREAD and make it run FUNCTION.
1667 The interrupt is asynchronous, and can occur anywhere with the exception of
1668 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1670 FUNCTION is called with interrupts disabled, under
1671 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1672 enable interrupts internally, in most cases FUNCTION should either enter
1673 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1674 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1676 When a thread receives multiple interrupts, they are executed in the order
1677 they were sent -- first in, first out.
1679 This means that a great degree of care is required to use INTERRUPT-THREAD
1680 safely and sanely in a production environment. The general recommendation is
1681 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1682 entirely from production environments -- it is simply exceedingly hard to use
1683 correctly.
1685 With those caveats in mind, what you need to know when using it:
1687 * If calling FUNCTION causes a non-local transfer of control (ie. an
1688 unwind), all normal cleanup forms will be executed.
1690 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1691 it is just as if that had happened due to a regular GO, THROW, or
1692 RETURN-FROM: the interrupted cleanup form and those following it in the
1693 same UNWIND-PROTECT do not get executed.
1695 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1696 frankly an unreasonable expectation for third party libraries, especially
1697 given that asynch-unwind-safety does not compose: a function calling
1698 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1700 This means that in order for an asynch unwind to be safe, the entire
1701 callstack at the point of interruption needs to be asynch-unwind-safe.
1703 * In addition to asynch-unwind-safety you must consider the issue of
1704 reentrancy. INTERRUPT-THREAD can cause function that are never normally
1705 called recursively to be re-entered during their dynamic contour,
1706 which may cause them to misbehave. (Consider binding of special variables,
1707 values of global variables, etc.)
1709 Take together, these two restrict the \"safe\" things to do using
1710 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1711 interactive development use is using it to force entry to debugger to inspect
1712 the state of a thread:
1714 (interrupt-thread thread #'break)
1716 Short version: be careful out there."
1717 #!+(and (not sb-thread) win32)
1718 #!+(and (not sb-thread) win32)
1719 (declare (ignore thread))
1720 (with-interrupt-bindings
1721 (with-interrupts (funcall function)))
1722 #!-(and (not sb-thread) win32)
1723 (let ((os-thread (thread-os-thread thread)))
1724 (cond ((not os-thread)
1725 (error 'interrupt-thread-error :thread thread))
1727 (with-interruptions-lock (thread)
1728 ;; Append to the end of the interruptions queue. It's
1729 ;; O(N), but it does not hurt to slow interruptors down a
1730 ;; bit when the queue gets long.
1731 (setf (thread-interruptions thread)
1732 (append (thread-interruptions thread)
1733 (list (lambda ()
1734 (without-interrupts
1735 (allow-with-interrupts
1736 (funcall function))))))))
1737 (when (minusp (wake-thread os-thread))
1738 (error 'interrupt-thread-error :thread thread))))))
1740 (defun terminate-thread (thread)
1741 #!+sb-doc
1742 "Terminate the thread identified by THREAD, by interrupting it and
1743 causing it to call SB-EXT:ABORT-THREAD with :ALLOW-EXIT T.
1745 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that
1746 eg. thread executing
1748 (let (foo)
1749 (unwind-protect
1750 (progn
1751 (setf foo (get-foo))
1752 (work-on-foo foo))
1753 (when foo
1754 ;; An interrupt occurring inside the cleanup clause
1755 ;; will cause cleanups from the current UNWIND-PROTECT
1756 ;; to be dropped.
1757 (release-foo foo))))
1759 might miss calling RELEASE-FOO despite GET-FOO having returned true if
1760 the interrupt occurs inside the cleanup clause, eg. during execution
1761 of RELEASE-FOO.
1763 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need
1764 to use WITHOUT-INTERRUPTS:
1766 (let (foo)
1767 (sb-sys:without-interrupts
1768 (unwind-protect
1769 (progn
1770 (setf foo (sb-sys:allow-with-interrupts
1771 (get-foo)))
1772 (sb-sys:with-local-interrupts
1773 (work-on-foo foo)))
1774 (when foo
1775 (release-foo foo)))))
1777 Since most libraries using UNWIND-PROTECT do not do this, you should never
1778 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1779 (interrupt-thread thread (lambda () (abort-thread :allow-exit t))))
1781 (define-alien-routine "thread_yield" int)
1783 #!+sb-doc
1784 (setf (fdocumentation 'thread-yield 'function)
1785 "Yield the processor to other threads.")
1787 ;;; internal use only. If you think you need to use these, either you
1788 ;;; are an SBCL developer, are doing something that you should discuss
1789 ;;; with an SBCL developer first, or are doing something that you
1790 ;;; should probably discuss with a professional psychiatrist first
1791 #!+sb-thread
1792 (progn
1793 (defun %thread-sap (thread)
1794 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1795 (target (thread-os-thread thread)))
1796 (loop
1797 (when (sap= thread-sap (int-sap 0)) (return nil))
1798 (let ((os-thread (sap-ref-word thread-sap
1799 (* sb!vm:n-word-bytes
1800 sb!vm::thread-os-thread-slot))))
1801 (when (= os-thread target) (return thread-sap))
1802 (setf thread-sap
1803 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1804 sb!vm::thread-next-slot)))))))
1806 (defun %symbol-value-in-thread (symbol thread)
1807 ;; Prevent the thread from dying completely while we look for the TLS
1808 ;; area...
1809 (with-all-threads-lock
1810 (if (thread-alive-p thread)
1811 (let* ((offset (get-lisp-obj-address
1812 (sb!vm::symbol-tls-index symbol)))
1813 (obj (sap-ref-lispobj (%thread-sap thread) offset))
1814 (tl-val (get-lisp-obj-address obj)))
1815 (cond ((zerop offset)
1816 (values nil :no-tls-value))
1817 ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1818 (eql tl-val sb!vm:unbound-marker-widetag))
1819 (values nil :unbound-in-thread))
1821 (values obj :ok))))
1822 (values nil :thread-dead))))
1824 (defun %set-symbol-value-in-thread (symbol thread value)
1825 (with-pinned-objects (value)
1826 ;; Prevent the thread from dying completely while we look for the TLS
1827 ;; area...
1828 (with-all-threads-lock
1829 (if (thread-alive-p thread)
1830 (let ((offset (get-lisp-obj-address
1831 (sb!vm::symbol-tls-index symbol))))
1832 (cond ((zerop offset)
1833 (values nil :no-tls-value))
1835 (setf (sap-ref-lispobj (%thread-sap thread) offset)
1836 value)
1837 (values value :ok))))
1838 (values nil :thread-dead)))))
1840 (define-alien-variable tls-index-start unsigned-int)
1842 ;; Get values from the TLS area of the current thread.
1843 (defun %thread-local-references ()
1844 ;; TLS-INDEX-START is a word number relative to thread base.
1845 ;; *FREE-TLS-INDEX* - which is only manipulated by machine code - is an
1846 ;; offset from thread base to the next usable TLS cell as a raw word
1847 ;; manifesting in Lisp as a fixnum. Convert it from byte number to word
1848 ;; number before using it as the upper bound for the sequential scan.
1849 (loop for index from tls-index-start
1850 ;; On x86-64, mask off the sign bit. It is used as a semaphore.
1851 below (ash (logand #!+x86-64 most-positive-fixnum
1852 sb!vm::*free-tls-index*)
1853 (+ (- sb!vm:word-shift) sb!vm:n-fixnum-tag-bits))
1854 for obj = (sb!kernel:%make-lisp-obj
1855 (sb!sys:sap-int (sb!vm::current-thread-offset-sap index)))
1856 unless (or (member (widetag-of obj)
1857 `(,sb!vm:no-tls-value-marker-widetag
1858 ,sb!vm:unbound-marker-widetag))
1859 (typep obj '(or fixnum character))
1860 (memq obj seen))
1861 collect obj into seen
1862 finally (return seen))))
1864 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1865 #!+sb-doc
1866 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1867 on success.
1869 If the value cannot be retrieved (because the thread has exited or because it
1870 has no local binding for NAME) and ERRORP is true signals an error of type
1871 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1872 NIL, and a secondary value of NIL.
1874 Can also be used with SETF to change the thread-local value of SYMBOL.
1876 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1877 mechanism for inter-thread communication."
1878 (declare (symbol symbol) (thread thread))
1879 #!+sb-thread
1880 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1881 (if (eq :ok status)
1882 (values res t)
1883 (if errorp
1884 (error 'symbol-value-in-thread-error
1885 :name symbol
1886 :thread thread
1887 :info (list :read status))
1888 (values nil nil))))
1889 #!-sb-thread
1890 (if (boundp symbol)
1891 (values (symbol-value symbol) t)
1892 (if errorp
1893 (error 'symbol-value-in-thread-error
1894 :name symbol
1895 :thread thread
1896 :info (list :read :unbound-in-thread))
1897 (values nil nil))))
1899 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1900 (declare (symbol symbol) (thread thread))
1901 #!+sb-thread
1902 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1903 (if (eq :ok status)
1904 (values res t)
1905 (if errorp
1906 (error 'symbol-value-in-thread-error
1907 :name symbol
1908 :thread thread
1909 :info (list :write status))
1910 (values nil nil))))
1911 #!-sb-thread
1912 (if (boundp symbol)
1913 (values (setf (symbol-value symbol) value) t)
1914 (if errorp
1915 (error 'symbol-value-in-thread-error
1916 :name symbol
1917 :thread thread
1918 :info (list :write :unbound-in-thread))
1919 (values nil nil))))
1923 ;;;; Stepping
1925 (defun thread-stepping ()
1926 (make-lisp-obj
1927 (sap-ref-word (current-thread-sap)
1928 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1930 (defun (setf thread-stepping) (value)
1931 (setf (sap-ref-word (current-thread-sap)
1932 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1933 (get-lisp-obj-address value)))