1 ;;;; support for threads in the target machine
3 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; This software is derived from the CMU CL system, which was
7 ;;;; written at Carnegie Mellon University and released into the
8 ;;;; public domain. The software is in the public domain and is
9 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
10 ;;;; files for more information.
12 (in-package "SB!THREAD")
16 ;;; Locks don't come any simpler -- or more lightweight than this. While
17 ;;; this is probably a premature optimization for most users, we still
18 ;;; need it internally for implementing condition variables outside Futex
21 (defmacro with-cas-lock
((place) &body body
)
23 "Runs BODY with interrupts disabled and *CURRENT-THREAD* compare-and-swapped
24 into PLACE instead of NIL. PLACE must be a place acceptable to
25 COMPARE-AND-SWAP, and must initially hold NIL.
27 WITH-CAS-LOCK is suitable mostly when the critical section needing protection
28 is very small, and cost of allocating a separate lock object would be
29 prohibitive. While it is the most lightweight locking constructed offered by
30 SBCL, it is also the least scalable if the section is heavily contested or
33 WITH-CAS-LOCK can be entered recursively."
35 (%with-cas-lock
(,place
) ,@body
)))
37 (defmacro %with-cas-lock
((place) &body body
&environment env
)
38 (with-unique-names (owner self
)
39 (multiple-value-bind (vars vals old new cas-form read-form
)
40 (sb!ext
:get-cas-expansion place env
)
41 `(let* (,@(mapcar #'list vars vals
)
45 (,self
*current-thread
*)
50 (unless (eq ,owner
,self
)
51 (loop until
(loop repeat
100
55 (not (setf ,owner
,cas-form
)))
58 do
(sb!ext
:spin-loop-hint
))
61 (unless (eq ,owner
,self
)
64 (unless (eq ,old
,cas-form
)
65 (bug "Failed to release CAS lock!")))))))))
69 (define-condition thread-error
(error)
70 ((thread :reader thread-error-thread
:initarg
:thread
))
73 "Conditions of type THREAD-ERROR are signalled when thread operations fail.
74 The offending thread is initialized by the :THREAD initialization argument and
75 read by the function THREAD-ERROR-THREAD."))
77 (define-condition simple-thread-error
(thread-error simple-condition
)
80 (define-condition thread-deadlock
(thread-error)
81 ((cycle :initarg
:cycle
:reader thread-deadlock-cycle
))
83 (lambda (condition stream
)
84 (let* ((*print-circle
* t
)
85 (cycle (thread-deadlock-cycle condition
))
87 (format stream
"Deadlock cycle detected:~%")
88 (loop for part
= (pop cycle
)
90 do
(format stream
" ~S~% waited for:~% ~S~% owned by:~%"
93 (format stream
" ~S~%" start
)))))
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
))
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
)
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."))))))
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
)
127 (format s
"Joining thread failed: thread ~A ~
128 did not return normally."
129 (thread-error-thread c
)))
131 (format s
"Joining thread timed out: thread ~A ~
132 did not exit in time."
133 (thread-error-thread c
)))
135 (format s
"In thread ~A, attempt to join the current ~
137 (thread-error-thread c
))))))
140 "Signalled when joining a thread fails due to abnormal exit of the thread
141 to be joined. The offending thread can be accessed using
142 THREAD-ERROR-THREAD."))
144 (define-deprecated-function :late
"1.0.29.17" join-thread-error-thread thread-error-thread
146 (thread-error-thread condition
))
148 (define-condition interrupt-thread-error
(thread-error) ()
149 (:report
(lambda (c s
)
150 (format s
"Interrupt thread failed: thread ~A has exited."
151 (thread-error-thread c
))))
154 "Signalled when interrupting a thread fails because the thread has already
155 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
157 (define-deprecated-function :late
"1.0.29.17" interrupt-thread-error-thread thread-error-thread
159 (thread-error-thread condition
))
161 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
162 ;;; necessary because threads are only supported with the conservative
163 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
164 ;;; are treated as references.
166 ;;; set the doc here because in early-thread FDOCUMENTATION is not
169 (setf (fdocumentation '*current-thread
* 'variable
)
170 "Bound in each thread to the thread itself.")
174 (fdocumentation 'thread-name
'function
)
175 "Name of the thread. Can be assigned to using SETF. Thread names can be
176 arbitrary printable objects, and need not be unique.")
178 (defmethod print-object ((thread thread
) stream
)
179 (print-unreadable-object (thread stream
:type t
:identity t
)
180 (let* ((cookie (list thread
))
181 (info (if (thread-alive-p thread
)
184 (join-thread thread
:default cookie
))))
185 (state (if (eq :running info
)
188 (thread-waiting-for thread
))))
191 (list "waiting on:" (cdr thing
)
192 "timeout: " (car thing
)))
196 (list "waiting on:" thing
))))
197 (if (eq cookie
(car info
))
200 (values (when (eq :finished state
)
204 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
210 (defun print-lock (lock name owner stream
)
211 (let ((*print-circle
* t
))
212 (print-unreadable-object (lock stream
:type t
:identity
(not name
))
214 (format stream
"~@[~S ~]~2I~_owner: ~S" name owner
)
215 (format stream
"~@[~S ~](free)" name
)))))
217 (defmethod print-object ((mutex mutex
) stream
)
218 (print-lock mutex
(mutex-name mutex
) (mutex-owner mutex
) stream
))
220 (defun thread-alive-p (thread)
222 "Return T if THREAD is still alive. Note that the return value is
223 potentially stale even before the function returns, as the thread may exit at
225 (thread-%alive-p thread
))
227 (defun thread-ephemeral-p (thread)
229 "Return T if THREAD is `ephemeral', which indicates that this thread is
230 used by SBCL for internal purposes, and specifically that it knows how to
231 to terminate this thread cleanly prior to core file saving without signalling
232 an error in that case."
233 (thread-%ephemeral-p thread
))
235 ;; A thread is eligible for gc iff it has finished and there are no
236 ;; more references to it. This list is supposed to keep a reference to
237 ;; all running threads.
238 (defvar *all-threads
* ())
239 (defvar *all-threads-lock
* (make-mutex :name
"all threads lock"))
241 (defvar *default-alloc-signal
* nil
)
243 (defmacro with-all-threads-lock
(&body body
)
244 `(with-system-mutex (*all-threads-lock
*)
247 (defun list-all-threads ()
249 "Return a list of the live threads. Note that the return value is
250 potentially stale even before the function returns, as new threads may be
251 created and old ones may exit at any time."
252 (with-all-threads-lock
253 (copy-list *all-threads
*)))
255 ;;; used by debug-int.lisp to access interrupt contexts
257 ;;; The two uses immediately below of (unsigned-byte 27) are arbitrary,
258 ;;; as a more reasonable type restriction is an integer from 0 to
259 ;;; (+ (primitive-object-size
260 ;;; (find 'thread *primitive-objects* :key #'primitive-object-name))
261 ;;; MAX-INTERRUPTS) ; defined only for C in 'interrupt.h'
263 ;;; The x86 32-bit port is helped slightly by having a stricter constraint
264 ;;; than the (unsigned-byte 32) from its DEFKNOWN of this function.
265 ;;; Ideally a single defknown would work for any backend because the thread
266 ;;; structure is, after all, defined in the generic objdefs. But the VM needs
267 ;;; the defknown before the VOP, and this file comes too late, so we'd
268 ;;; need to pick some other place - maybe 'thread.lisp'?
270 #!-
(or sb-fluid sb-thread
) (declaim (inline sb
!vm
::current-thread-offset-sap
))
272 (defun sb!vm
::current-thread-offset-sap
(n)
273 (declare (type (unsigned-byte 27) n
))
274 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t
)))
275 (* n sb
!vm
:n-word-bytes
)))
278 (defun sb!vm
::current-thread-offset-sap
(n)
279 (declare (type (unsigned-byte 27) n
))
280 (sb!vm
::current-thread-offset-sap n
))
282 (declaim (inline current-thread-sap
))
283 (defun current-thread-sap ()
284 (sb!vm
::current-thread-offset-sap sb
!vm
::thread-this-slot
))
286 (declaim (inline current-thread-os-thread
))
287 (defun current-thread-os-thread ()
289 (sap-int (sb!vm
::current-thread-offset-sap sb
!vm
::thread-os-thread-slot
))
293 (defvar *initial-thread
* nil
)
294 (defvar *make-thread-lock
*)
296 (defun init-initial-thread ()
297 (/show0
"Entering INIT-INITIAL-THREAD")
298 (setf sb
!impl
::*exit-lock
* (make-mutex :name
"Exit Lock")
299 *make-thread-lock
* (make-mutex :name
"Make-Thread Lock"))
300 (let ((initial-thread (%make-thread
:name
"main thread"
302 (setf (thread-os-thread initial-thread
) (current-thread-os-thread)
303 *initial-thread
* initial-thread
304 *current-thread
* initial-thread
)
305 (grab-mutex (thread-result-lock *initial-thread
*))
306 ;; Either *all-threads* is empty or it contains exactly one thread
307 ;; in case we are in reinit since saving core with multiple
308 ;; threads doesn't work.
309 (setq *all-threads
* (list initial-thread
))))
311 (defun main-thread ()
313 "Returns the main thread of the process."
316 (defun main-thread-p (&optional
(thread *current-thread
*))
318 "True if THREAD, defaulting to current thread, is the main thread of the process."
319 (eq thread
*initial-thread
*))
321 (defmacro return-from-thread
(values-form &key allow-exit
)
323 "Unwinds from and terminates the current thread, with values from
324 VALUES-FORM as the results visible to JOIN-THREAD.
326 If current thread is the main thread of the process (see
327 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
328 terminating the main thread would terminate the entire process. If
329 ALLOW-EXIT is true, returning from the main thread is equivalent to
330 calling SB-EXT:EXIT with :CODE 0 and :ABORT NIL.
332 See also: ABORT-THREAD and SB-EXT:EXIT."
333 `(%return-from-thread
(multiple-value-list ,values-form
) ,allow-exit
))
335 (defun %return-from-thread
(values allow-exit
)
336 (let ((self *current-thread
*))
337 (cond ((main-thread-p self
)
339 (error 'simple-thread-error
340 :format-control
"~@<Tried to return ~S as values from main thread, ~
341 but exit was not allowed.~:@>"
342 :format-arguments
(list values
)
344 (sb!ext
:exit
:code
0))
346 (throw '%return-from-thread
(values-list values
))))))
348 (defun abort-thread (&key allow-exit
)
350 "Unwinds from and terminates the current thread abnormally, causing
351 JOIN-THREAD on current thread to signal an error unless a
352 default-value is provided.
354 If current thread is the main thread of the process (see
355 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
356 terminating the main thread would terminate the entire process. If
357 ALLOW-EXIT is true, aborting the main thread is equivalent to calling
358 SB-EXT:EXIT code 1 and :ABORT NIL.
360 Invoking the initial ABORT restart established by MAKE-THREAD is
361 equivalent to calling ABORT-THREAD in other than main threads.
362 However, whereas ABORT restart may be rebound, ABORT-THREAD always
363 unwinds the entire thread. (Behaviour of the initial ABORT restart for
364 main thread depends on the :TOPLEVEL argument to
365 SB-EXT:SAVE-LISP-AND-DIE.)
367 See also: RETURN-FROM-THREAD and SB-EXT:EXIT."
368 (let ((self *current-thread
*))
369 (cond ((main-thread-p self
)
371 (error 'simple-thread-error
372 :format-control
"~@<Tried to abort initial thread, but ~
373 exit was not allowed.~:@>"))
374 (sb!ext
:exit
:code
1))
376 ;; We /could/ use TOPLEVEL-CATCHER or %END-OF-THE-WORLD as well, but
377 ;; this seems tidier. Those to are a bit too overloaded already.
378 (throw '%abort-thread t
)))))
381 ;;;; Aliens, low level stuff
383 (define-alien-routine "kill_safely"
385 (os-thread #!-alpha unsigned
#!+alpha unsigned-int
)
388 (define-alien-routine "wake_thread"
390 (os-thread unsigned
))
394 ;; FIXME it would be good to define what a thread id is or isn't
395 ;; (our current assumption is that it's a fixnum). It so happens
396 ;; that on Linux it's a pid, but it might not be on posix thread
398 (define-alien-routine ("create_thread" %create-thread
)
399 unsigned
(lisp-fun-address unsigned
))
401 (declaim (inline %block-deferrable-signals
))
402 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals
)
407 (defun block-deferrable-signals ()
408 (%block-deferrable-signals
0 0))
412 (declaim (inline futex-wait %futex-wait futex-wake
))
414 (define-alien-routine ("futex_wait" %futex-wait
) int
415 (word unsigned
) (old-value unsigned
)
416 (to-sec long
) (to-usec unsigned-long
))
418 (defun futex-wait (word old to-sec to-usec
)
420 (%futex-wait word old to-sec to-usec
)))
422 (define-alien-routine "futex_wake"
423 int
(word unsigned
) (n unsigned-long
))))
425 (defmacro with-deadlocks
((thread lock
&optional
(timeout nil timeoutp
)) &body forms
)
426 (with-unique-names (n-thread n-lock new n-timeout
)
427 `(let* ((,n-thread
,thread
)
429 (,n-timeout
,(when timeoutp
431 (when sb
!impl
::*deadline
*
432 sb
!impl
::*deadline-seconds
*))))
434 ;; Using CONS tells the rest of the system there's a
435 ;; timeout in place, so it isn't considered a deadlock.
436 (cons ,n-timeout
,n-lock
)
438 (declare (dynamic-extent ,new
))
439 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
440 ;; in places where interrupts should already be disabled.
443 (setf (thread-waiting-for ,n-thread
) ,new
)
446 ;; Interrupt handlers and GC save and restore any
447 ;; previous wait marks using WITHOUT-DEADLOCKS below.
448 (setf (thread-waiting-for ,n-thread
) nil
)
449 (barrier (:write
))))))
454 (setf (fdocumentation 'make-mutex
'function
)
456 (fdocumentation 'mutex-name
'function
)
457 "The name of the mutex. Setfable.")
459 #!+(and sb-thread sb-futex
)
461 (locally (declare (sb!ext
:muffle-conditions sb
!ext
:compiler-note
))
462 (define-structure-slot-addressor mutex-state-address
465 ;; Important: current code assumes these are fixnums or other
466 ;; lisp objects that don't need pinning.
467 (defconstant +lock-free
+ 0)
468 (defconstant +lock-taken
+ 1)
469 (defconstant +lock-contested
+ 2))
471 (defun mutex-owner (mutex)
473 "Current owner of the mutex, NIL if the mutex is free. Naturally,
474 this is racy by design (another thread may acquire the mutex after
475 this function returns), it is intended for informative purposes. For
476 testing whether the current thread is holding a mutex see
478 ;; Make sure to get the current value.
479 (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil nil
))
481 (sb!ext
:defglobal
**deadlock-lock
** nil
)
483 #!+(or (not sb-thread
) sb-futex
)
484 (defstruct (waitqueue (:constructor make-waitqueue
(&key name
)))
487 (name nil
:type
(or null thread-name
))
488 #!+(and sb-thread sb-futex
)
491 #!+(and sb-thread
(not sb-futex
))
492 (defstruct (waitqueue (:constructor make-waitqueue
(&key name
)))
495 (name nil
:type
(or null thread-name
))
496 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
497 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
498 ;; lock. In most cases this should be uncontested thanks to the mutex --
499 ;; the only case where that might not be true is when CONDITION-WAIT
500 ;; unwinds and %WAITQUEUE-DROP is called.
505 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
506 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
507 (defun check-deadlock ()
508 (let* ((self *current-thread
*)
511 (thread-waiting-for self
))))
512 (labels ((detect-deadlock (lock)
513 (let ((other-thread (mutex-%owner lock
)))
514 (cond ((not other-thread
))
515 ((eq self other-thread
)
517 (with-cas-lock ((symbol-value '**deadlock-lock
**))
518 (prog1 (deadlock-chain self origin
)
519 ;; We're now committed to signaling the
520 ;; error and breaking the deadlock, so
521 ;; mark us as no longer waiting on the
522 ;; lock. This ensures that a single
523 ;; deadlock is reported in only one
524 ;; thread, and that we don't look like
525 ;; we're waiting on the lock when print
526 ;; stuff -- because that may lead to
527 ;; further deadlock checking, in turn
528 ;; possibly leading to a bogus vicious
529 ;; metacycle on PRINT-OBJECT.
530 (setf (thread-waiting-for self
) nil
)))))
531 (error 'thread-deadlock
532 :thread
*current-thread
*
535 (let ((other-lock (progn
537 (thread-waiting-for other-thread
))))
538 ;; If the thread is waiting with a timeout OTHER-LOCK
539 ;; is a cons, and we don't consider it a deadlock -- since
540 ;; it will time out on its own sooner or later.
541 (when (mutex-p other-lock
)
542 (detect-deadlock other-lock
)))))))
543 (deadlock-chain (thread lock
)
544 (let* ((other-thread (mutex-owner lock
))
545 (other-lock (when other-thread
547 (thread-waiting-for other-thread
))))
548 (cond ((not other-thread
)
549 ;; The deadlock is gone -- maybe someone unwound
550 ;; from the same deadlock already?
551 (return-from check-deadlock nil
))
553 ;; There's a timeout -- no deadlock.
554 (return-from check-deadlock nil
))
555 ((waitqueue-p other-lock
)
557 (return-from check-deadlock nil
))
558 ((eq self other-thread
)
560 (list (list thread lock
)))
563 (cons (cons thread lock
)
564 (deadlock-chain other-thread other-lock
))
565 ;; Again, the deadlock is gone?
566 (return-from check-deadlock nil
)))))))
567 ;; Timeout means there is no deadlock
568 (when (mutex-p origin
)
569 (detect-deadlock origin
)
572 (defun %try-mutex
(mutex new-owner
)
573 (declare (type mutex mutex
) (optimize (speed 3)))
575 (let ((old (mutex-%owner mutex
)))
576 (when (eq new-owner old
)
577 (error "Recursive lock attempt ~S." mutex
))
580 (error "Strange deadlock on ~S in an unithreaded build?" mutex
))
581 #!-
(and sb-thread sb-futex
)
583 ;; Don't even bother to try to CAS if it looks bad.
584 (not (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil new-owner
)))
585 #!+(and sb-thread sb-futex
)
586 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
587 (when (eql +lock-free
+ (sb!ext
:compare-and-swap
(mutex-state mutex
)
590 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil new-owner
)))
592 (bug "Old owner in free mutex: ~S" prev
))
596 (defun %%wait-for-mutex
(mutex new-owner to-sec to-usec stop-sec stop-usec
)
597 (declare (type mutex mutex
) (optimize (speed 3)))
599 (declare (ignore to-sec to-usec
))
605 (not (mutex-%owner mutex
)))
606 (not (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil
608 do
(return-from cas t
)
611 (sb!ext
:spin-loop-hint
))
612 ;; Check for pending interrupts.
613 (with-interrupts nil
)))
614 (declare (dynamic-extent #'cas
))
615 (sb!impl
::%%wait-for
#'cas stop-sec stop-usec
))
617 ;; This is a fairly direct translation of the Mutex 2 algorithm from
618 ;; "Futexes are Tricky" by Ulrich Drepper.
620 (when (eql +lock-free
+ old
)
621 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
)
624 (bug "Old owner in free mutex: ~S" prev
))
625 (return-from %%wait-for-mutex t
)))))
626 (prog ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
627 +lock-free
+ +lock-taken
+)))
628 ;; Got it right off the bat?
631 ;; Mark it as contested, and sleep. (Exception: it was just released.)
632 (when (or (eql +lock-contested
+ old
)
633 (not (eql +lock-free
+
634 (sb!ext
:compare-and-swap
635 (mutex-state mutex
) +lock-taken
+ +lock-contested
+))))
636 (when (eql 1 (with-pinned-objects (mutex)
637 (futex-wait (mutex-state-address mutex
)
638 (get-lisp-obj-address +lock-contested
+)
641 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
643 ;; 1 = ETIMEDOUT ***DONE***
644 ;; 2 = EINTR, a spurious wakeup
645 (return-from %%wait-for-mutex nil
)))
646 ;; Try to get it, still marking it as contested.
648 (sb!ext
:compare-and-swap
(mutex-state mutex
) +lock-free
+ +lock-contested
+))
649 ;; Update timeout if necessary.
651 (setf (values to-sec to-usec
)
652 (sb!impl
::relative-decoded-times stop-sec stop-usec
)))
657 (defun %wait-for-mutex
(mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep
)
658 (declare (sb!ext
:muffle-conditions sb
!ext
:compiler-note
))
659 (with-deadlocks (self mutex timeout
)
660 (with-interrupts (check-deadlock))
663 (return-from %wait-for-mutex
664 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec
)
667 ;; FIXME: substract elapsed time from timeout...
668 (setf (values to-sec to-usec stop-sec stop-usec deadlinep
)
669 (decode-timeout timeout
))
672 (define-deprecated-function :early
"1.0.37.33" get-mutex
(grab-mutex)
673 (mutex &optional new-owner
(waitp t
) (timeout nil
))
674 (declare (ignorable waitp timeout
))
675 (let ((new-owner (or new-owner
*current-thread
*)))
676 (or (%try-mutex mutex new-owner
)
679 (multiple-value-call #'%wait-for-mutex
680 mutex new-owner timeout
(decode-timeout timeout
))))))
682 (defun grab-mutex (mutex &key
(waitp t
) (timeout nil
))
684 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
685 the mutex is not immediately available, sleep until it is available.
687 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
688 GRAB-MUTEX should try to acquire the lock in the contested case.
690 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
691 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
692 that GRAB-MUTEX did -not- acquire the lock.
696 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
700 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
703 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
704 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
705 allows the call to be interrupted from sleep.
707 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
708 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
709 DEADLINE-TIMEOUT if the global deadline was due already on entering
712 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
715 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
718 (declare (ignorable waitp timeout
))
719 (let ((self *current-thread
*))
720 (or (%try-mutex mutex self
)
723 (multiple-value-call #'%wait-for-mutex
724 mutex self timeout
(decode-timeout timeout
))))))
726 (defun release-mutex (mutex &key
(if-not-owner :punt
))
728 "Release MUTEX by setting it to NIL. Wake up threads waiting for
731 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
734 If the current thread is not the owner of the mutex then it silently
735 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
736 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
737 IF-NOT-OWNER is :FORCE)."
738 (declare (type mutex mutex
))
739 ;; Order matters: set owner to NIL before releasing state.
740 (let* ((self *current-thread
*)
741 (old-owner (sb!ext
:compare-and-swap
(mutex-%owner mutex
) self nil
)))
742 (unless (eq self old-owner
)
744 ((:punt
) (return-from release-mutex nil
))
746 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner
))
748 (setf (mutex-%owner mutex
) nil
)
749 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
752 #!+(and sb-thread sb-futex
)
754 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
755 ;; unsigned-byte type this can be used:
757 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
758 ;; (unless (eql old +lock-free+)
759 ;; (setf (mutex-state mutex) +lock-free+)
760 ;; (with-pinned-objects (mutex)
761 ;; (futex-wake (mutex-state-address mutex) 1))))
762 (let ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
763 +lock-taken
+ +lock-free
+)))
764 (when (eql old
+lock-contested
+)
765 (sb!ext
:compare-and-swap
(mutex-state mutex
)
766 +lock-contested
+ +lock-free
+)
767 (with-pinned-objects (mutex)
768 (futex-wake (mutex-state-address mutex
) 1))))
772 ;;;; Waitqueues/condition variables
774 #!+(and sb-thread
(not sb-futex
))
776 (defun %waitqueue-enqueue
(thread queue
)
777 (setf (thread-waiting-for thread
) queue
)
778 (let ((head (waitqueue-%head queue
))
779 (tail (waitqueue-%tail queue
))
782 (setf (waitqueue-%head queue
) new
))
784 (setf (cdr tail
) new
))
785 (setf (waitqueue-%tail queue
) new
)
787 (defun %waitqueue-drop
(thread queue
)
788 (setf (thread-waiting-for thread
) nil
)
789 (let ((head (waitqueue-%head queue
)))
790 (do ((list head
(cdr list
))
793 (eq (car list
) thread
))
795 (let ((rest (cdr list
)))
797 (setf (cdr prev
) rest
))
799 (setf (waitqueue-%head queue
) rest
802 (setf (waitqueue-%tail queue
) prev
)))))))
804 (defun %waitqueue-wakeup
(queue n
)
806 (loop while
(plusp n
)
807 for next
= (let ((head (waitqueue-%head queue
))
808 (tail (waitqueue-%tail queue
)))
811 (setf (waitqueue-%head queue
) nil
812 (waitqueue-%tail queue
) nil
)
813 (setf (waitqueue-%head queue
) (cdr head
)))
816 do
(when (eq queue
(sb!ext
:compare-and-swap
817 (thread-waiting-for next
) queue nil
))
821 (defmethod print-object ((waitqueue waitqueue
) stream
)
822 (print-unreadable-object (waitqueue stream
:type t
:identity t
)
823 (format stream
"~@[~A~]" (waitqueue-name waitqueue
))))
826 (setf (fdocumentation 'waitqueue-name
'function
)
827 "The name of the waitqueue. Setfable."
828 (fdocumentation 'make-waitqueue
'function
)
829 "Create a waitqueue.")
831 #!+(and sb-thread sb-futex
)
832 (locally (declare (sb!ext
:muffle-conditions sb
!ext
:compiler-note
))
833 (define-structure-slot-addressor waitqueue-token-address
837 (declaim (inline %condition-wait
))
838 (defun %condition-wait
(queue mutex
839 timeout to-sec to-usec stop-sec stop-usec deadlinep
)
841 (declare (ignore queue mutex to-sec to-usec stop-sec stop-usec deadlinep
))
843 (sb!ext
:wait-for nil
:timeout timeout
) ; Yeah...
845 (let ((me *current-thread
*))
847 (assert (eq me
(mutex-%owner mutex
)))
848 (let ((status :interrupted
))
849 ;; Need to disable interrupts so that we don't miss grabbing
850 ;; the mutex on our way out.
856 (%with-cas-lock
((waitqueue-%owner queue
))
857 (%waitqueue-enqueue me queue
))
858 (release-mutex mutex
)
860 (or (flet ((wakeup ()
862 (unless (eq queue
(thread-waiting-for me
))
864 (declare (dynamic-extent #'wakeup
))
865 (allow-with-interrupts
866 (sb!impl
::%%wait-for
#'wakeup stop-sec stop-usec
)))
869 (with-pinned-objects (queue me
)
870 (setf (waitqueue-token queue
) me
)
871 (release-mutex mutex
)
872 ;; Now we go to sleep using futex-wait. If anyone else
873 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
874 ;; this comment, it will change the token, and so futex-wait
875 ;; returns immediately instead of sleeping. Ergo, no lost
876 ;; wakeup. We may get spurious wakeups, but that's ok.
878 (case (allow-with-interrupts
879 (futex-wait (waitqueue-token-address queue
)
880 (get-lisp-obj-address me
)
881 ;; our way of saying "no
889 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
891 ;; 2 = EINTR, a spurious wakeup
894 (%with-cas-lock
((waitqueue-%owner queue
))
895 (if (eq queue
(thread-waiting-for me
))
896 (%waitqueue-drop me queue
)
897 (unless (eq :ok status
)
898 ;; CONDITION-NOTIFY thinks we've been woken up, but really
899 ;; we're unwinding. Wake someone else up.
900 (%waitqueue-wakeup queue
1))))
901 ;; Update timeout for mutex re-aquisition unless we are
902 ;; already past the requested timeout.
903 (when (and (eq :ok status
) to-sec
)
904 (setf (values to-sec to-usec
)
905 (sb!impl
::relative-decoded-times stop-sec stop-usec
))
906 (when (and (zerop to-sec
) (not (plusp to-usec
)))
907 (setf status
:timeout
)))
908 ;; If we ran into deadline, try to get the mutex before
909 ;; signaling. If we don't unwind it will look like a normal
910 ;; return from user perspective.
911 (when (and (eq :timeout status
) deadlinep
)
912 (let ((got-it (%try-mutex mutex me
)))
913 (allow-with-interrupts
916 (return-from %condition-wait t
))
918 ;; The deadline may have changed.
919 (setf (values to-sec to-usec stop-sec stop-usec deadlinep
)
920 (decode-timeout timeout
))
921 (setf status
:ok
))))))
922 ;; Re-acquire the mutex for normal return.
923 (when (eq :ok status
)
924 (unless (or (%try-mutex mutex me
)
925 (allow-with-interrupts
926 (%wait-for-mutex mutex me timeout
928 stop-sec stop-usec deadlinep
)))
929 (setf status
:timeout
)))))
930 ;; Determine actual return value. :ok means (potentially
931 ;; spurious) wakeup => T. :timeout => NIL.
935 (multiple-value-bind (sec usec
)
936 (sb!impl
::relative-decoded-times stop-sec stop-usec
)
942 ;; The only case we return normally without re-acquiring
943 ;; the mutex is when there is a :TIMEOUT that runs out.
944 (bug "%CONDITION-WAIT: invalid status on normal return: ~S" status
))))))
945 (declaim (notinline %condition-wait
))
947 (defun condition-wait (queue mutex
&key timeout
)
949 "Atomically release MUTEX and start waiting on QUEUE until another thread
950 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on
951 QUEUE, at which point we re-acquire MUTEX and return T.
953 Spurious wakeups are possible.
955 If TIMEOUT is given, it is the maximum number of seconds to wait,
956 including both waiting for the wakeup and the time to re-acquire
957 MUTEX. When neither a wakeup nor a re-acquisition occurs within the
958 given time, returns NIL without re-acquiring MUTEX.
960 If CONDITION-WAIT unwinds, it may do so with or without MUTEX being
963 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY or
964 CONDITION-BROADCAST having occurred, the correct way to write code
965 that uses CONDITION-WAIT is to loop around the call, checking the
969 (defvar *queue* (make-waitqueue))
970 (defvar *lock* (make-mutex))
973 (defun pop-data (&optional timeout)
976 do (or (condition-wait *queue* *lock* :timeout timeout)
977 ;; Lock not held, must unwind without touching *data*.
978 (return-from pop-data nil)))
982 (defun push-data (data)
985 (condition-notify *queue*)))
988 (locally (declare (inline %condition-wait
))
989 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep
)
990 (decode-timeout timeout
)
992 (%condition-wait queue mutex timeout
993 to-sec to-usec stop-sec stop-usec deadlinep
)))))
995 (defun condition-notify (queue &optional
(n 1))
997 "Notify N threads waiting on QUEUE.
999 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
1000 must be held by this thread during this call."
1002 (declare (ignore queue n
))
1004 (error "Not supported in unithread builds.")
1006 (declare (type (and fixnum
(integer 1)) n
))
1007 (/show0
"Entering CONDITION-NOTIFY")
1011 (with-cas-lock ((waitqueue-%owner queue
))
1012 (%waitqueue-wakeup queue n
))
1015 ;; No problem if >1 thread notifies during the comment in condition-wait:
1016 ;; as long as the value in queue-data isn't the waiting thread's id, it
1017 ;; matters not what it is -- using the queue object itself is handy.
1019 ;; XXX we should do something to ensure that the result of this setf
1020 ;; is visible to all CPUs.
1022 ;; ^-- surely futex_wake() involves a memory barrier?
1023 (setf (waitqueue-token queue
) queue
)
1024 (with-pinned-objects (queue)
1025 (futex-wake (waitqueue-token-address queue
) n
)))))
1027 (defun condition-broadcast (queue)
1029 "Notify all threads waiting on QUEUE.
1031 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
1032 must be held by this thread during this call."
1033 (condition-notify queue
1034 ;; On a 64-bit platform truncating M-P-F to an int
1035 ;; results in -1, which wakes up only one thread.
1037 most-positive-fixnum
)))
1042 (defstruct (semaphore (:constructor make-semaphore
1043 (&key name
((:count %count
) 0))))
1045 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
1046 should be considered an implementation detail, and may change in the
1048 (name nil
:type
(or null thread-name
))
1049 (%count
0 :type
(integer 0))
1050 (waitcount 0 :type sb
!vm
:word
)
1051 (mutex (make-mutex))
1052 (queue (make-waitqueue)))
1055 (setf (fdocumentation 'semaphore-name
'function
)
1056 "The name of the semaphore INSTANCE. Setfable."
1057 (fdocumentation 'make-semaphore
'function
)
1058 "Create a semaphore with the supplied COUNT and NAME.")
1060 (defstruct (semaphore-notification (:constructor make-semaphore-notification
())
1063 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
1064 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
1065 multiple threads are using the same notification object in parallel."
1066 (%status nil
:type boolean
))
1069 (setf (fdocumentation 'make-semaphore-notification
'function
)
1070 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
1073 (declaim (inline semaphore-notification-status
))
1074 (defun semaphore-notification-status (semaphore-notification)
1076 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
1077 SEMAPHORE-NOTIFICATION has succeeded since the notification object was created
1080 (semaphore-notification-%status semaphore-notification
))
1082 (declaim (inline clear-semaphore-notification
))
1083 (defun clear-semaphore-notification (semaphore-notification)
1085 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
1086 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
1088 (setf (semaphore-notification-%status semaphore-notification
) nil
)))
1090 (declaim (inline semaphore-count
))
1091 (defun semaphore-count (instance)
1093 "Returns the current count of the semaphore INSTANCE."
1095 (semaphore-%count instance
))
1097 (declaim (ftype (sfunction (semaphore (integer 1) (or boolean real
)
1098 (or null semaphore-notification
) symbol
)
1100 %decrement-semaphore
))
1101 (defun %decrement-semaphore
(semaphore n wait notification context
)
1102 (when (and notification
(semaphore-notification-status notification
))
1103 (with-simple-restart (continue "Clear notification status and continue.")
1104 (error "~@<Semaphore notification object status not cleared on ~
1105 entry to ~S on ~S.~:@>"
1107 (clear-semaphore-notification notification
))
1109 ;; A more direct implementation based directly on futexes should be
1112 ;; We need to disable interrupts so that we don't forget to
1113 ;; decrement the waitcount (which would happen if an asynch
1114 ;; interrupt should catch us on our way out from the loop.)
1116 ;; FIXME: No timeout on initial mutex acquisition.
1117 (with-system-mutex ((semaphore-mutex semaphore
) :allow-with-interrupts t
)
1118 (flet ((success (new-count)
1120 (setf (semaphore-%count semaphore
) new-count
)
1122 (setf (semaphore-notification-%status notification
) t
)))))
1123 ;; Quick check: can we decrement right away? If not, return or
1124 ;; enter the wait loop.
1126 ((let ((old-count (semaphore-%count semaphore
)))
1127 (when (>= old-count n
)
1128 (success (- old-count n
)))))
1133 (binding* ((old-count nil
)
1134 (timeout (when (realp wait
) wait
))
1135 ((to-sec to-usec stop-sec stop-usec deadlinep
)
1137 (decode-timeout timeout
))))
1138 ;; Need to use ATOMIC-INCF despite the lock, because
1139 ;; on our way out from here we might not be locked
1140 ;; anymore -- so another thread might be tweaking this
1141 ;; in parallel using ATOMIC-DECF. No danger over
1142 ;; overflow, since there it at most one increment per
1143 ;; thread waiting on the semaphore.
1144 (sb!ext
:atomic-incf
(semaphore-waitcount semaphore
))
1145 (loop until
(>= (setf old-count
(semaphore-%count semaphore
)) n
)
1146 do
(multiple-value-bind (wakeup-p remaining-sec remaining-usec
)
1148 (semaphore-queue semaphore
)
1149 (semaphore-mutex semaphore
)
1150 timeout to-sec to-usec stop-sec stop-usec deadlinep
)
1151 (when (or (not wakeup-p
)
1152 (and (eql remaining-sec
0)
1153 (eql remaining-usec
0)))
1154 (return-from %decrement-semaphore nil
)) ; timeout
1156 (setf to-sec remaining-sec
1157 to-usec remaining-usec
))))
1158 (success (- old-count n
)))
1159 ;; Need to use ATOMIC-DECF as we may unwind without the
1161 (sb!ext
:atomic-decf
(semaphore-waitcount semaphore
))))))))
1163 (declaim (ftype (sfunction (semaphore &key
1165 (:timeout
(real (0)))
1166 (:notification semaphore-notification
))
1167 (or null
(integer 0)))
1169 (defun wait-on-semaphore (semaphore &key
(n 1) timeout notification
)
1171 "Decrement the count of SEMAPHORE by N if the count would not be negative.
1173 Else blocks until the semaphore can be decremented. Returns the new count of
1174 SEMAPHORE on success.
1176 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
1177 cannot be decremented in that time, returns NIL without decrementing the
1180 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
1181 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
1182 decrements the count, the status is set to T."
1183 (%decrement-semaphore
1184 semaphore n
(or timeout t
) notification
'wait-on-semaphore
))
1186 (declaim (ftype (sfunction (semaphore &optional
1187 (integer 1) semaphore-notification
)
1188 (or null
(integer 0)))
1190 (defun try-semaphore (semaphore &optional
(n 1) notification
)
1192 "Try to decrement the count of SEMAPHORE by N. If the count were to
1193 become negative, punt and return NIL, otherwise return the new count of
1196 If NOTIFICATION is given it must be a semaphore notification object
1197 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1198 the status is set to T."
1199 (%decrement-semaphore semaphore n nil notification
'try-semaphore
))
1201 (defun signal-semaphore (semaphore &optional
(n 1))
1203 "Increment the count of SEMAPHORE by N. If there are threads waiting
1204 on this semaphore, then N of them is woken up."
1205 (declare (type (integer 1) n
))
1206 ;; Need to disable interrupts so that we don't lose a wakeup after
1207 ;; we have incremented the count.
1208 (with-system-mutex ((semaphore-mutex semaphore
) :allow-with-interrupts t
)
1209 (let ((waitcount (semaphore-waitcount semaphore
))
1210 (count (incf (semaphore-%count semaphore
) n
)))
1211 (when (plusp waitcount
)
1212 (condition-notify (semaphore-queue semaphore
) (min waitcount count
))))))
1215 ;;;; Job control, independent listeners
1218 (lock (make-mutex :name
"session lock"))
1220 (interactive-threads nil
)
1221 (interactive-threads-queue (make-waitqueue)))
1223 (defvar *session
* nil
)
1225 ;;; The debugger itself tries to acquire the session lock, don't let
1226 ;;; funny situations (like getting a sigint while holding the session
1227 ;;; lock) occur. At the same time we need to allow interrupts while
1228 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1229 ;;; be interruptible.
1231 ;;; Take care: we sometimes need to obtain the session lock while
1232 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1233 ;;; _after_ getting a session lock! (Deadlock risk.)
1235 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1237 (defmacro with-session-lock
((session) &body body
)
1238 `(with-system-mutex ((session-lock ,session
) :allow-with-interrupts t
)
1241 (defun new-session ()
1242 (make-session :threads
(list *current-thread
*)
1243 :interactive-threads
(list *current-thread
*)))
1245 (defun init-job-control ()
1246 (/show0
"Entering INIT-JOB-CONTROL")
1247 (setf *session
* (new-session))
1248 (/show0
"Exiting INIT-JOB-CONTROL"))
1250 (defun %delete-thread-from-session
(thread session
)
1251 (with-session-lock (session)
1252 (setf (session-threads session
)
1253 ;; DELQ never conses, but DELETE does. (FIXME)
1254 (delq thread
(session-threads session
))
1255 (session-interactive-threads session
)
1256 (delq thread
(session-interactive-threads session
)))))
1258 (defun call-with-new-session (fn)
1259 (%delete-thread-from-session
*current-thread
* *session
*)
1260 (let ((*session
* (new-session)))
1263 (defmacro with-new-session
(args &body forms
)
1264 (declare (ignore args
)) ;for extensibility
1265 (sb!int
:with-unique-names
(fb-name)
1266 `(labels ((,fb-name
() ,@forms
))
1267 (call-with-new-session (function ,fb-name
)))))
1269 ;;; Remove thread from its session, if it has one.
1271 (defun handle-thread-exit (thread)
1272 (/show0
"HANDLING THREAD EXIT")
1273 (when *exit-in-process
*
1275 ;; Lisp-side cleanup
1276 (with-all-threads-lock
1277 (setf (thread-%alive-p thread
) nil
)
1278 (setf (thread-os-thread thread
) 0)
1279 (setq *all-threads
* (delq thread
*all-threads
*))
1281 (%delete-thread-from-session thread
*session
*))))
1283 (defun %exit-other-threads
()
1284 ;; Grabbing this lock prevents new threads from
1285 ;; being spawned, and guarantees that *ALL-THREADS*
1287 (with-deadline (:seconds nil
:override t
)
1288 (grab-mutex *make-thread-lock
*)
1289 (let ((timeout sb
!ext
:*exit-timeout
*)
1290 (code *exit-in-process
*)
1291 (current *current-thread
*)
1294 (dolist (thread (list-all-threads))
1295 (cond ((eq thread current
))
1296 ((main-thread-p thread
)
1301 (terminate-thread thread
)
1302 (push thread joinees
))
1303 (interrupt-thread-error ())))))
1304 (with-progressive-timeout (time-left :seconds timeout
)
1305 (dolist (thread joinees
)
1306 (join-thread thread
:default t
:timeout
(time-left)))
1307 ;; Need to defer till others have joined, because when main
1308 ;; thread exits, we're gone. Can't use TERMINATE-THREAD -- would
1309 ;; get the exit code wrong.
1315 (setf *exit-in-process
* (list code
))
1316 (throw 'sb
!impl
::%end-of-the-world t
)))
1317 (interrupt-thread-error ()))
1318 ;; Normally this never finishes, as once the main-thread unwinds we
1319 ;; exit with the right code, but if times out before that happens,
1320 ;; we will exit after returning -- or rathe racing the main thread
1321 ;; to calling OS-EXIT.
1322 (join-thread main
:default t
:timeout
(time-left)))))))
1324 (defun terminate-session ()
1326 "Kill all threads in session except for this one. Does nothing if current
1327 thread is not the foreground thread."
1328 ;; FIXME: threads created in other threads may escape termination
1330 (with-session-lock (*session
*)
1331 (and (eq *current-thread
*
1332 (car (session-interactive-threads *session
*)))
1333 (session-threads *session
*)))))
1334 ;; do the kill after dropping the mutex; unwind forms in dying
1335 ;; threads may want to do session things
1336 (dolist (thread to-kill
)
1337 (unless (eq thread
*current-thread
*)
1338 ;; terminate the thread but don't be surprised if it has
1339 ;; exited in the meantime
1340 (handler-case (terminate-thread thread
)
1341 (interrupt-thread-error ()))))))
1343 ;;; called from top of invoke-debugger
1344 (defun debugger-wait-until-foreground-thread (stream)
1346 "Returns T if thread had been running in background, NIL if it was
1348 (declare (ignore stream
))
1352 (with-session-lock (*session
*)
1353 (not (member *current-thread
*
1354 (session-interactive-threads *session
*))))
1357 (defun get-foreground ()
1360 (let ((was-foreground t
))
1362 (/show0
"Looping in GET-FOREGROUND")
1363 (with-session-lock (*session
*)
1364 (let ((int-t (session-interactive-threads *session
*)))
1365 (when (eq (car int-t
) *current-thread
*)
1366 (unless was-foreground
1367 (format *query-io
* "Resuming thread ~A~%" *current-thread
*))
1368 (return-from get-foreground t
))
1369 (setf was-foreground nil
)
1370 (unless (member *current-thread
* int-t
)
1371 (setf (cdr (last int-t
))
1372 (list *current-thread
*)))
1374 (session-interactive-threads-queue *session
*)
1375 (session-lock *session
*)))))))
1377 (defun release-foreground (&optional next
)
1379 "Background this thread. If NEXT is supplied, arrange for it to
1380 have the foreground next."
1381 #!-sb-thread
(declare (ignore next
))
1384 (with-session-lock (*session
*)
1385 (when (rest (session-interactive-threads *session
*))
1386 (setf (session-interactive-threads *session
*)
1387 (delete *current-thread
* (session-interactive-threads *session
*))))
1389 (setf (session-interactive-threads *session
*)
1391 (delete next
(session-interactive-threads *session
*)))))
1392 (condition-broadcast (session-interactive-threads-queue *session
*))))
1394 (defun interactive-threads (&optional
(session *session
*))
1396 "Return the interactive threads of SESSION defaulting to the current
1398 (session-interactive-threads session
))
1400 (defun foreground-thread (&optional
(session *session
*))
1402 "Return the foreground thread of SESSION defaulting to the current
1404 (first (interactive-threads session
)))
1406 (defun make-listener-thread (tty-name)
1407 (assert (probe-file tty-name
))
1408 (let* ((in (sb!unix
:unix-open
(namestring tty-name
) sb
!unix
:o_rdwr
#o666
))
1409 (out (sb!unix
:unix-dup in
))
1410 (err (sb!unix
:unix-dup in
)))
1411 (labels ((thread-repl ()
1412 (sb!unix
::unix-setsid
)
1413 (let* ((sb!impl
::*stdin
*
1414 (make-fd-stream in
:input t
:buffering
:line
1417 (make-fd-stream out
:output t
:buffering
:line
1420 (make-fd-stream err
:output t
:buffering
:line
1423 (make-fd-stream err
:input t
:output t
1426 (sb!impl
::*descriptor-handlers
* nil
))
1427 (with-new-session ()
1429 (sb!impl
::toplevel-repl nil
)
1430 (sb!int
:flush-standard-output-streams
))))))
1431 (make-thread #'thread-repl
))))
1437 (defun initial-thread-function-trampoline
1438 (thread setup-sem real-function thread-list arguments arg1 arg2 arg3
)
1439 ;; In time we'll move some of the binding presently done in C here
1442 ;; KLUDGE: Here we have a magic list of variables that are not
1443 ;; thread-safe for one reason or another. As people report problems
1444 ;; with the thread safety of certain variables, (e.g. "*print-case* in
1445 ;; multiple threads broken", sbcl-devel 2006-07-14), we add a few more
1446 ;; bindings here. The Right Thing is probably some variant of
1447 ;; Allegro's *cl-default-special-bindings*, as that is at least
1448 ;; accessible to users to secure their own libraries.
1449 ;; --njf, 2006-07-15
1451 ;; As it is, this lambda must not cons until we are ready to run
1452 ;; GC. Be very careful.
1453 (let* ((*current-thread
* thread
)
1454 (*restart-clusters
* nil
)
1455 (*handler-clusters
* sb
!kernel
::**initial-handler-clusters
**)
1456 (*exit-in-process
* nil
)
1457 (sb!impl
::*deadline
* nil
)
1458 (sb!impl
::*deadline-seconds
* nil
)
1459 (sb!impl
::*step-out
* nil
)
1460 ;; internal reader variables
1461 (sb!impl
::*token-buf-pool
* nil
)
1462 ;; internal printer variables
1463 (sb!impl
::*previous-case
* nil
)
1464 (sb!impl
::*previous-readtable-case
* nil
)
1465 (sb!impl
::*internal-symbol-output-fun
* #'error
)
1466 (sb!impl
::*ignored-package-locks
* :invalid
)
1467 (sb!impl
::*descriptor-handlers
* nil
)) ; serve-event
1468 (declare (inline make-restart
)) ;; to allow DX-allocation
1470 (setf sb
!vm
:*alloc-signal
* *default-alloc-signal
*)
1471 (setf (thread-os-thread thread
) (current-thread-os-thread))
1472 (with-mutex ((thread-result-lock thread
))
1473 ;; Normally the list is allocated in the parent thread to
1474 ;; avoid consing in a nascent thread.
1476 (let* ((thread-list (or thread-list
1477 (list thread thread
)))
1478 (session-cons (cdr thread-list
)))
1479 (with-all-threads-lock
1480 (setf (cdr thread-list
) *all-threads
*
1481 *all-threads
* thread-list
))
1482 (let ((session *session
*))
1483 (with-session-lock (session)
1484 (setf (cdr session-cons
) (session-threads session
)
1485 (session-threads session
) session-cons
))))
1486 (setf (thread-%alive-p thread
) t
)
1489 (signal-semaphore setup-sem
)
1490 ;; setup-sem was dx-allocated, set it to NIL so that the
1491 ;; backtrace doesn't get confused
1492 (setf setup-sem nil
))
1494 ;; Using handling-end-of-the-world would be a bit tricky
1495 ;; due to other catches and interrupts, so we essentially
1496 ;; re-implement it here. Once and only once more.
1497 (catch 'sb
!impl
::toplevel-catcher
1498 (catch 'sb
!impl
::%end-of-the-world
1499 (catch '%abort-thread
1500 (restart-bind ((abort
1502 (throw '%abort-thread nil
))
1505 (format stream
"~@<abort thread (~a)~@:>"
1506 *current-thread
*))))
1509 (with-local-interrupts
1510 (setf *gc-inhibit
* nil
) ;for foreign callbacks
1511 (sb!unix
::unblock-deferrable-signals
)
1512 (setf (thread-result thread
)
1514 (multiple-value-list
1516 (catch '%return-from-thread
1517 (if (listp arguments
)
1518 (apply real-function arguments
)
1519 (funcall real-function arg1 arg2 arg3
)))
1520 (when *exit-in-process
*
1521 (sb!impl
::call-exit-hooks
))))
1523 (sb!kernel
::gc-safepoint
))))
1524 ;; we're going down, can't handle interrupts
1525 ;; sanely anymore. gc remains enabled.
1526 (block-deferrable-signals)
1527 ;; we don't want to run interrupts in a dead
1528 ;; thread when we leave without-interrupts.
1529 ;; this potentially causes important
1530 ;; interupts to be lost: sigint comes to
1532 (setq *interrupt-pending
* nil
)
1534 (setq *thruption-pending
* nil
)
1535 (handle-thread-exit thread
)))))))))
1538 (defun make-thread (function &key name arguments ephemeral
)
1540 "Create a new thread of NAME that runs FUNCTION with the argument
1541 list designator provided (defaults to no argument). Thread exits when
1542 the function returns. The return values of FUNCTION are kept around
1543 and can be retrieved by JOIN-THREAD.
1545 Invoking the initial ABORT restart established by MAKE-THREAD
1546 terminates the thread.
1548 See also: RETURN-FROM-THREAD, ABORT-THREAD."
1549 #!-sb-thread
(declare (ignore function name arguments ephemeral
))
1550 #!-sb-thread
(error "Not supported in unithread builds.")
1551 #!+sb-thread
(assert (or (atom arguments
)
1552 (null (cdr (last arguments
))))
1554 "Argument passed to ~S, ~S, is an improper list."
1555 'make-thread arguments
)
1557 (let ((thread (%make-thread
:name name
:%ephemeral-p ephemeral
)))
1558 (declare (inline make-semaphore
1561 (let* ((setup-sem (make-semaphore :name
"Thread setup semaphore"))
1562 (real-function (coerce function
'function
))
1563 (arguments (ensure-list arguments
))
1564 #!+(or win32 darwin
)
1565 (fp-modes (dpb 0 sb
!vm
::float-sticky-bits
;; clear accrued bits
1566 (sb!vm
:floating-point-modes
)))
1567 ;; Allocate in the parent
1568 (thread-list (list thread thread
)))
1569 (declare (dynamic-extent setup-sem
))
1570 (dx-flet ((initial-thread-function ()
1571 ;; Inherit parent thread's FP modes
1572 #!+(or win32 darwin
)
1573 (setf (sb!vm
:floating-point-modes
) fp-modes
)
1574 ;; As it is, this lambda must not cons until we are
1575 ;; ready to run GC. Be very careful.
1576 (initial-thread-function-trampoline
1577 thread setup-sem real-function thread-list
1578 arguments nil nil nil
)))
1579 ;; If the starting thread is stopped for gc before it signals
1580 ;; the semaphore then we'd be stuck.
1581 (assert (not *gc-inhibit
*))
1582 ;; Keep INITIAL-FUNCTION in the dynamic extent until the child
1583 ;; thread is initialized properly. Wrap the whole thing in
1584 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to
1586 (with-system-mutex (*make-thread-lock
*)
1588 (%create-thread
(get-lisp-obj-address #'initial-thread-function
)))
1590 (wait-on-semaphore setup-sem
)))))
1591 (or thread
(error "Could not create a new thread."))))
1593 (defun join-thread (thread &key
(default nil defaultp
) timeout
)
1595 "Suspend current thread until THREAD exits. Return the result values
1596 of the thread function.
1598 If THREAD does not exit within TIMEOUT seconds and DEFAULT is
1599 supplied, return two values: 1) DEFAULT 2) :TIMEOUT. If DEFAULT is not
1600 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-PROBLEM equal
1603 If THREAD does not exit normally (i.e. aborted) and DEFAULT is
1604 supplied, return two values: 1) DEFAULT 2) :ABORT. If DEFAULT is not
1605 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-PROBLEM equal
1608 If THREAD is the current thread, signal a JOIN-THREAD-ERROR with
1609 JOIN-THREAD-PROBLEM equal to :SELF-JOIN.
1611 Trying to join the main thread causes JOIN-THREAD to block until
1612 TIMEOUT occurs or the process exits: when the main thread exits, the
1613 entire process exits.
1615 NOTE: Return convention in case of a timeout is experimental and
1617 (when (eq thread
*current-thread
*)
1618 (error 'join-thread-error
:thread thread
:problem
:self-join
))
1620 (let ((lock (thread-result-lock thread
))
1627 (allow-with-interrupts
1628 ;; Don't use the timeout if the thread is
1629 ;; not alive anymore.
1630 (grab-mutex lock
:timeout
(and (thread-alive-p thread
)
1632 ((listp (thread-result thread
))
1633 (return-from join-thread
1634 (values-list (thread-result thread
))))
1636 (setf problem
:abort
)))
1638 (release-mutex lock
))))
1640 (values default problem
)
1641 (error 'join-thread-error
:thread thread
:problem problem
))))
1643 (defun destroy-thread (thread)
1644 (terminate-thread thread
))
1647 (declaim (sb!ext
:deprecated
1648 :late
("SBCL" "1.2.15")
1649 (function destroy-thread
:replacement terminate-thread
)))
1652 (defun enter-foreign-callback (arg1 arg2 arg3
)
1653 (initial-thread-function-trampoline
1654 (make-foreign-thread :name
"foreign callback")
1655 nil
#'sb
!alien
::enter-alien-callback nil t arg1 arg2 arg3
))
1657 (defmacro with-interruptions-lock
((thread) &body body
)
1658 `(with-system-mutex ((thread-interruptions-lock ,thread
))
1661 ;;; Called from the signal handler.
1662 #!-
(or sb-thruption win32
)
1663 (defun run-interruption ()
1664 (let ((interruption (with-interruptions-lock (*current-thread
*)
1665 (pop (thread-interruptions *current-thread
*)))))
1666 ;; If there is more to do, then resignal and let the normal
1667 ;; interrupt deferral mechanism take care of the rest. From the
1668 ;; OS's point of view the signal we are in the handler for is no
1669 ;; longer pending, so the signal will not be lost.
1670 (when (thread-interruptions *current-thread
*)
1671 (kill-safely (thread-os-thread *current-thread
*) sb
!unix
:sigpipe
))
1673 (funcall interruption
))))
1676 (defun run-interruption ()
1677 (in-interruption () ;the non-thruption code does this in the signal handler
1678 (let ((interruption (with-interruptions-lock (*current-thread
*)
1679 (pop (thread-interruptions *current-thread
*)))))
1681 (funcall interruption
)
1682 ;; I tried implementing this function as an explicit LOOP, because
1683 ;; if we are currently processing the thruption queue, why not do
1684 ;; all of them in one go instead of one-by-one?
1686 ;; I still think LOOPing would be basically the right thing
1687 ;; here. But suppose some interruption unblocked deferrables.
1688 ;; Will the next one be happy with that? The answer is "no", at
1689 ;; least in the sense that there are tests which check that
1690 ;; deferrables are blocked at the beginning of a thruption, and
1691 ;; races that make those tests fail. Whether the tests are
1692 ;; misguided or not, it seems easier/cleaner to loop implicitly
1693 ;; -- and it's also what AK had implemented in the first place.
1695 ;; The implicit loop is achieved by returning to C, but having C
1696 ;; call back to us immediately. The runtime will reset the sigmask
1697 ;; in the mean time.
1699 (setf *thruption-pending
* t
)))))
1701 (defun interrupt-thread (thread function
)
1703 "Interrupt THREAD and make it run FUNCTION.
1705 The interrupt is asynchronous, and can occur anywhere with the exception of
1706 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1708 FUNCTION is called with interrupts disabled, under
1709 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1710 enable interrupts internally, in most cases FUNCTION should either enter
1711 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1712 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1714 When a thread receives multiple interrupts, they are executed in the order
1715 they were sent -- first in, first out.
1717 This means that a great degree of care is required to use INTERRUPT-THREAD
1718 safely and sanely in a production environment. The general recommendation is
1719 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1720 entirely from production environments -- it is simply exceedingly hard to use
1723 With those caveats in mind, what you need to know when using it:
1725 * If calling FUNCTION causes a non-local transfer of control (ie. an
1726 unwind), all normal cleanup forms will be executed.
1728 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1729 it is just as if that had happened due to a regular GO, THROW, or
1730 RETURN-FROM: the interrupted cleanup form and those following it in the
1731 same UNWIND-PROTECT do not get executed.
1733 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1734 frankly an unreasonable expectation for third party libraries, especially
1735 given that asynch-unwind-safety does not compose: a function calling
1736 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1738 This means that in order for an asynch unwind to be safe, the entire
1739 callstack at the point of interruption needs to be asynch-unwind-safe.
1741 * In addition to asynch-unwind-safety you must consider the issue of
1742 reentrancy. INTERRUPT-THREAD can cause function that are never normally
1743 called recursively to be re-entered during their dynamic contour,
1744 which may cause them to misbehave. (Consider binding of special variables,
1745 values of global variables, etc.)
1747 Take together, these two restrict the \"safe\" things to do using
1748 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1749 interactive development use is using it to force entry to debugger to inspect
1750 the state of a thread:
1752 (interrupt-thread thread #'break)
1754 Short version: be careful out there."
1755 #!+(and (not sb-thread
) win32
)
1756 #!+(and (not sb-thread
) win32
)
1757 (declare (ignore thread
))
1758 (with-interrupt-bindings
1759 (with-interrupts (funcall function
)))
1760 #!-
(and (not sb-thread
) win32
)
1761 (let ((os-thread (thread-os-thread thread
)))
1762 (cond ((not os-thread
)
1763 (error 'interrupt-thread-error
:thread thread
))
1765 (with-interruptions-lock (thread)
1766 ;; Append to the end of the interruptions queue. It's
1767 ;; O(N), but it does not hurt to slow interruptors down a
1768 ;; bit when the queue gets long.
1769 (setf (thread-interruptions thread
)
1770 (append (thread-interruptions thread
)
1773 (allow-with-interrupts
1774 (funcall function
))))))))
1775 (when (minusp (wake-thread os-thread
))
1776 (error 'interrupt-thread-error
:thread thread
))))))
1778 (defun terminate-thread (thread)
1780 "Terminate the thread identified by THREAD, by interrupting it and
1781 causing it to call SB-EXT:ABORT-THREAD with :ALLOW-EXIT T.
1783 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that
1784 eg. thread executing
1789 (setf foo (get-foo))
1792 ;; An interrupt occurring inside the cleanup clause
1793 ;; will cause cleanups from the current UNWIND-PROTECT
1795 (release-foo foo))))
1797 might miss calling RELEASE-FOO despite GET-FOO having returned true if
1798 the interrupt occurs inside the cleanup clause, eg. during execution
1801 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need
1802 to use WITHOUT-INTERRUPTS:
1805 (sb-sys:without-interrupts
1808 (setf foo (sb-sys:allow-with-interrupts
1810 (sb-sys:with-local-interrupts
1813 (release-foo foo)))))
1815 Since most libraries using UNWIND-PROTECT do not do this, you should never
1816 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1817 (interrupt-thread thread
(lambda () (abort-thread :allow-exit t
))))
1819 (define-alien-routine "thread_yield" int
)
1822 (setf (fdocumentation 'thread-yield
'function
)
1823 "Yield the processor to other threads.")
1825 ;;; internal use only. If you think you need to use these, either you
1826 ;;; are an SBCL developer, are doing something that you should discuss
1827 ;;; with an SBCL developer first, or are doing something that you
1828 ;;; should probably discuss with a professional psychiatrist first
1831 (defun %thread-sap
(thread)
1832 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t
))))
1833 (target (thread-os-thread thread
)))
1835 (when (sap= thread-sap
(int-sap 0)) (return nil
))
1836 (let ((os-thread (sap-ref-word thread-sap
1837 (* sb
!vm
:n-word-bytes
1838 sb
!vm
::thread-os-thread-slot
))))
1839 (when (= os-thread target
) (return thread-sap
))
1841 (sap-ref-sap thread-sap
(* sb
!vm
:n-word-bytes
1842 sb
!vm
::thread-next-slot
)))))))
1844 (defun %symbol-value-in-thread
(symbol thread
)
1845 ;; Prevent the thread from dying completely while we look for the TLS
1847 (with-all-threads-lock
1848 (if (thread-alive-p thread
)
1849 (let* ((offset (get-lisp-obj-address (symbol-tls-index symbol
)))
1850 (obj (sap-ref-lispobj (%thread-sap thread
) offset
))
1851 (tl-val (get-lisp-obj-address obj
)))
1852 (cond ((zerop offset
)
1853 (values nil
:no-tls-value
))
1854 ((or (eql tl-val sb
!vm
:no-tls-value-marker-widetag
)
1855 (eql tl-val sb
!vm
:unbound-marker-widetag
))
1856 (values nil
:unbound-in-thread
))
1859 (values nil
:thread-dead
))))
1861 (defun %set-symbol-value-in-thread
(symbol thread value
)
1862 (with-pinned-objects (value)
1863 ;; Prevent the thread from dying completely while we look for the TLS
1865 (with-all-threads-lock
1866 (if (thread-alive-p thread
)
1867 (let ((offset (get-lisp-obj-address (symbol-tls-index symbol
))))
1868 (cond ((zerop offset
)
1869 (values nil
:no-tls-value
))
1871 (setf (sap-ref-lispobj (%thread-sap thread
) offset
)
1873 (values value
:ok
))))
1874 (values nil
:thread-dead
)))))
1876 (define-alien-variable tls-index-start unsigned-int
)
1878 ;; Get values from the TLS area of the current thread.
1879 (defun %thread-local-references
()
1880 ;; TLS-INDEX-START is a word number relative to thread base.
1881 ;; *FREE-TLS-INDEX* - which is only manipulated by machine code - is an
1882 ;; offset from thread base to the next usable TLS cell as a raw word
1883 ;; manifesting in Lisp as a fixnum. Convert it from byte number to word
1884 ;; number before using it as the upper bound for the sequential scan.
1885 (loop for index from tls-index-start
1886 ;; On x86-64, mask off the sign bit. It is used as a semaphore.
1887 below
(ash (logand #!+x86-64 most-positive-fixnum
1888 sb
!vm
::*free-tls-index
*)
1889 (+ (- sb
!vm
:word-shift
) sb
!vm
:n-fixnum-tag-bits
))
1890 for obj
= (sb!kernel
:%make-lisp-obj
1891 (sb!sys
:sap-int
(sb!vm
::current-thread-offset-sap index
)))
1892 unless
(or (member (widetag-of obj
)
1893 `(,sb
!vm
:no-tls-value-marker-widetag
1894 ,sb
!vm
:unbound-marker-widetag
))
1895 (typep obj
'(or fixnum character
))
1897 collect obj into seen
1898 finally
(return seen
))))
1900 (defun symbol-value-in-thread (symbol thread
&optional
(errorp t
))
1902 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1905 If the value cannot be retrieved (because the thread has exited or because it
1906 has no local binding for NAME) and ERRORP is true signals an error of type
1907 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1908 NIL, and a secondary value of NIL.
1910 Can also be used with SETF to change the thread-local value of SYMBOL.
1912 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1913 mechanism for inter-thread communication."
1914 (declare (symbol symbol
) (thread thread
))
1916 (multiple-value-bind (res status
) (%symbol-value-in-thread symbol thread
)
1920 (error 'symbol-value-in-thread-error
1923 :info
(list :read status
))
1927 (values (symbol-value symbol
) t
)
1929 (error 'symbol-value-in-thread-error
1932 :info
(list :read
:unbound-in-thread
))
1935 (defun (setf symbol-value-in-thread
) (value symbol thread
&optional
(errorp t
))
1936 (declare (symbol symbol
) (thread thread
))
1938 (multiple-value-bind (res status
) (%set-symbol-value-in-thread symbol thread value
)
1942 (error 'symbol-value-in-thread-error
1945 :info
(list :write status
))
1949 (values (setf (symbol-value symbol
) value
) t
)
1951 (error 'symbol-value-in-thread-error
1954 :info
(list :write
:unbound-in-thread
))
1961 (defun thread-stepping ()
1962 (sap-ref-lispobj (current-thread-sap)
1963 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
)))
1965 (defun (setf thread-stepping
) (value)
1966 (setf (sap-ref-lispobj (current-thread-sap)
1967 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
))