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 (def!method 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 (def!method 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 (define-structure-slot-addressor mutex-state-address
464 ;; Important: current code assumes these are fixnums or other
465 ;; lisp objects that don't need pinning.
466 (defconstant +lock-free
+ 0)
467 (defconstant +lock-taken
+ 1)
468 (defconstant +lock-contested
+ 2))
470 (defun mutex-owner (mutex)
472 "Current owner of the mutex, NIL if the mutex is free. Naturally,
473 this is racy by design (another thread may acquire the mutex after
474 this function returns), it is intended for informative purposes. For
475 testing whether the current thread is holding a mutex see
477 ;; Make sure to get the current value.
478 (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil nil
))
480 (sb!ext
:defglobal
**deadlock-lock
** nil
)
482 #!+(or (not sb-thread
) sb-futex
)
483 (defstruct (waitqueue (:constructor make-waitqueue
(&key name
)))
486 (name nil
:type
(or null thread-name
))
487 #!+(and sb-thread sb-futex
)
490 #!+(and sb-thread
(not sb-futex
))
491 (defstruct (waitqueue (:constructor make-waitqueue
(&key name
)))
494 (name nil
:type
(or null thread-name
))
495 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
496 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
497 ;; lock. In most cases this should be uncontested thanks to the mutex --
498 ;; the only case where that might not be true is when CONDITION-WAIT
499 ;; unwinds and %WAITQUEUE-DROP is called.
504 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
505 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
506 (defun check-deadlock ()
507 (let* ((self *current-thread
*)
510 (thread-waiting-for self
))))
511 (labels ((detect-deadlock (lock)
512 (let ((other-thread (mutex-%owner lock
)))
513 (cond ((not other-thread
))
514 ((eq self other-thread
)
516 (with-cas-lock ((symbol-value '**deadlock-lock
**))
517 (prog1 (deadlock-chain self origin
)
518 ;; We're now committed to signaling the
519 ;; error and breaking the deadlock, so
520 ;; mark us as no longer waiting on the
521 ;; lock. This ensures that a single
522 ;; deadlock is reported in only one
523 ;; thread, and that we don't look like
524 ;; we're waiting on the lock when print
525 ;; stuff -- because that may lead to
526 ;; further deadlock checking, in turn
527 ;; possibly leading to a bogus vicious
528 ;; metacycle on PRINT-OBJECT.
529 (setf (thread-waiting-for self
) nil
)))))
530 (error 'thread-deadlock
531 :thread
*current-thread
*
534 (let ((other-lock (progn
536 (thread-waiting-for other-thread
))))
537 ;; If the thread is waiting with a timeout OTHER-LOCK
538 ;; is a cons, and we don't consider it a deadlock -- since
539 ;; it will time out on its own sooner or later.
540 (when (mutex-p other-lock
)
541 (detect-deadlock other-lock
)))))))
542 (deadlock-chain (thread lock
)
543 (let* ((other-thread (mutex-owner lock
))
544 (other-lock (when other-thread
546 (thread-waiting-for other-thread
))))
547 (cond ((not other-thread
)
548 ;; The deadlock is gone -- maybe someone unwound
549 ;; from the same deadlock already?
550 (return-from check-deadlock nil
))
552 ;; There's a timeout -- no deadlock.
553 (return-from check-deadlock nil
))
554 ((waitqueue-p other-lock
)
556 (return-from check-deadlock nil
))
557 ((eq self other-thread
)
559 (list (list thread lock
)))
562 (cons (cons thread lock
)
563 (deadlock-chain other-thread other-lock
))
564 ;; Again, the deadlock is gone?
565 (return-from check-deadlock nil
)))))))
566 ;; Timeout means there is no deadlock
567 (when (mutex-p origin
)
568 (detect-deadlock origin
)
571 (defun %try-mutex
(mutex new-owner
)
572 (declare (type mutex mutex
) (optimize (speed 3)))
574 (let ((old (mutex-%owner mutex
)))
575 (when (eq new-owner old
)
576 (error "Recursive lock attempt ~S." mutex
))
579 (error "Strange deadlock on ~S in an unithreaded build?" mutex
))
580 #!-
(and sb-thread sb-futex
)
582 ;; Don't even bother to try to CAS if it looks bad.
583 (not (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil new-owner
)))
584 #!+(and sb-thread sb-futex
)
585 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
586 (when (eql +lock-free
+ (sb!ext
:compare-and-swap
(mutex-state mutex
)
589 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil new-owner
)))
591 (bug "Old owner in free mutex: ~S" prev
))
595 (defun %%wait-for-mutex
(mutex new-owner to-sec to-usec stop-sec stop-usec
)
596 (declare (type mutex mutex
) (optimize (speed 3)))
598 (declare (ignore to-sec to-usec
))
604 (not (mutex-%owner mutex
)))
605 (not (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil
607 do
(return-from cas t
)
610 (sb!ext
:spin-loop-hint
))
611 ;; Check for pending interrupts.
612 (with-interrupts nil
)))
613 (declare (dynamic-extent #'cas
))
614 (sb!impl
::%%wait-for
#'cas stop-sec stop-usec
))
616 ;; This is a fairly direct translation of the Mutex 2 algorithm from
617 ;; "Futexes are Tricky" by Ulrich Drepper.
619 (when (eql +lock-free
+ old
)
620 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
)
623 (bug "Old owner in free mutex: ~S" prev
))
624 (return-from %%wait-for-mutex t
)))))
625 (prog ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
626 +lock-free
+ +lock-taken
+)))
627 ;; Got it right off the bat?
630 ;; Mark it as contested, and sleep. (Exception: it was just released.)
631 (when (or (eql +lock-contested
+ old
)
632 (not (eql +lock-free
+
633 (sb!ext
:compare-and-swap
634 (mutex-state mutex
) +lock-taken
+ +lock-contested
+))))
635 (when (eql 1 (with-pinned-objects (mutex)
636 (futex-wait (mutex-state-address mutex
)
637 (get-lisp-obj-address +lock-contested
+)
640 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
642 ;; 1 = ETIMEDOUT ***DONE***
643 ;; 2 = EINTR, a spurious wakeup
644 (return-from %%wait-for-mutex nil
)))
645 ;; Try to get it, still marking it as contested.
647 (sb!ext
:compare-and-swap
(mutex-state mutex
) +lock-free
+ +lock-contested
+))
648 ;; Update timeout if necessary.
650 (setf (values to-sec to-usec
)
651 (sb!impl
::relative-decoded-times stop-sec stop-usec
)))
656 (defun %wait-for-mutex
(mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep
)
657 (with-deadlocks (self mutex timeout
)
658 (with-interrupts (check-deadlock))
661 (return-from %wait-for-mutex
662 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec
)
665 ;; FIXME: substract elapsed time from timeout...
666 (setf (values to-sec to-usec stop-sec stop-usec deadlinep
)
667 (decode-timeout timeout
))
670 (define-deprecated-function :early
"1.0.37.33" get-mutex
(grab-mutex)
671 (mutex &optional new-owner
(waitp t
) (timeout nil
))
672 (declare (ignorable waitp timeout
))
673 (let ((new-owner (or new-owner
*current-thread
*)))
674 (or (%try-mutex mutex new-owner
)
677 (multiple-value-call #'%wait-for-mutex
678 mutex new-owner timeout
(decode-timeout timeout
))))))
680 (defun grab-mutex (mutex &key
(waitp t
) (timeout nil
))
682 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
683 the mutex is not immediately available, sleep until it is available.
685 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
686 GRAB-MUTEX should try to acquire the lock in the contested case.
688 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
689 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
690 that GRAB-MUTEX did -not- acquire the lock.
694 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
698 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
701 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
702 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
703 allows the call to be interrupted from sleep.
705 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
706 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
707 DEADLINE-TIMEOUT if the global deadline was due already on entering
710 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
713 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
716 (declare (ignorable waitp timeout
))
717 (let ((self *current-thread
*))
718 (or (%try-mutex mutex self
)
721 (multiple-value-call #'%wait-for-mutex
722 mutex self timeout
(decode-timeout timeout
))))))
724 (defun release-mutex (mutex &key
(if-not-owner :punt
))
726 "Release MUTEX by setting it to NIL. Wake up threads waiting for
729 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
732 If the current thread is not the owner of the mutex then it silently
733 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
734 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
735 IF-NOT-OWNER is :FORCE)."
736 (declare (type mutex mutex
))
737 ;; Order matters: set owner to NIL before releasing state.
738 (let* ((self *current-thread
*)
739 (old-owner (sb!ext
:compare-and-swap
(mutex-%owner mutex
) self nil
)))
740 (unless (eq self old-owner
)
742 ((:punt
) (return-from release-mutex nil
))
744 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner
))
746 (setf (mutex-%owner mutex
) nil
)
747 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
750 #!+(and sb-thread sb-futex
)
752 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
753 ;; unsigned-byte type this can be used:
755 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
756 ;; (unless (eql old +lock-free+)
757 ;; (setf (mutex-state mutex) +lock-free+)
758 ;; (with-pinned-objects (mutex)
759 ;; (futex-wake (mutex-state-address mutex) 1))))
760 (let ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
761 +lock-taken
+ +lock-free
+)))
762 (when (eql old
+lock-contested
+)
763 (sb!ext
:compare-and-swap
(mutex-state mutex
)
764 +lock-contested
+ +lock-free
+)
765 (with-pinned-objects (mutex)
766 (futex-wake (mutex-state-address mutex
) 1))))
770 ;;;; Waitqueues/condition variables
772 #!+(and sb-thread
(not sb-futex
))
774 (defun %waitqueue-enqueue
(thread queue
)
775 (setf (thread-waiting-for thread
) queue
)
776 (let ((head (waitqueue-%head queue
))
777 (tail (waitqueue-%tail queue
))
780 (setf (waitqueue-%head queue
) new
))
782 (setf (cdr tail
) new
))
783 (setf (waitqueue-%tail queue
) new
)
785 (defun %waitqueue-drop
(thread queue
)
786 (setf (thread-waiting-for thread
) nil
)
787 (let ((head (waitqueue-%head queue
)))
788 (do ((list head
(cdr list
))
791 (eq (car list
) thread
))
793 (let ((rest (cdr list
)))
795 (setf (cdr prev
) rest
))
797 (setf (waitqueue-%head queue
) rest
800 (setf (waitqueue-%tail queue
) prev
)))))))
802 (defun %waitqueue-wakeup
(queue n
)
804 (loop while
(plusp n
)
805 for next
= (let ((head (waitqueue-%head queue
))
806 (tail (waitqueue-%tail queue
)))
809 (setf (waitqueue-%head queue
) nil
810 (waitqueue-%tail queue
) nil
)
811 (setf (waitqueue-%head queue
) (cdr head
)))
814 do
(when (eq queue
(sb!ext
:compare-and-swap
815 (thread-waiting-for next
) queue nil
))
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
))))
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
834 (declaim (inline %condition-wait
))
835 (defun %condition-wait
(queue mutex
836 timeout to-sec to-usec stop-sec stop-usec deadlinep
)
838 (declare (ignore queue mutex to-sec to-usec stop-sec stop-usec deadlinep
))
840 (sb!ext
:wait-for nil
:timeout timeout
) ; Yeah...
842 (let ((me *current-thread
*))
844 (assert (eq me
(mutex-%owner mutex
)))
845 (let ((status :interrupted
))
846 ;; Need to disable interrupts so that we don't miss grabbing
847 ;; the mutex on our way out.
853 (%with-cas-lock
((waitqueue-%owner queue
))
854 (%waitqueue-enqueue me queue
))
855 (release-mutex mutex
)
857 (or (flet ((wakeup ()
859 (unless (eq queue
(thread-waiting-for me
))
861 (declare (dynamic-extent #'wakeup
))
862 (allow-with-interrupts
863 (sb!impl
::%%wait-for
#'wakeup stop-sec stop-usec
)))
866 (with-pinned-objects (queue me
)
867 (setf (waitqueue-token queue
) me
)
868 (release-mutex mutex
)
869 ;; Now we go to sleep using futex-wait. If anyone else
870 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
871 ;; this comment, it will change the token, and so futex-wait
872 ;; returns immediately instead of sleeping. Ergo, no lost
873 ;; wakeup. We may get spurious wakeups, but that's ok.
875 (case (allow-with-interrupts
876 (futex-wait (waitqueue-token-address queue
)
877 (get-lisp-obj-address me
)
878 ;; our way of saying "no
886 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
888 ;; 2 = EINTR, a spurious wakeup
891 (%with-cas-lock
((waitqueue-%owner queue
))
892 (if (eq queue
(thread-waiting-for me
))
893 (%waitqueue-drop me queue
)
894 (unless (eq :ok status
)
895 ;; CONDITION-NOTIFY thinks we've been woken up, but really
896 ;; we're unwinding. Wake someone else up.
897 (%waitqueue-wakeup queue
1))))
898 ;; Update timeout for mutex re-aquisition unless we are
899 ;; already past the requested timeout.
900 (when (and (eq :ok status
) to-sec
)
901 (setf (values to-sec to-usec
)
902 (sb!impl
::relative-decoded-times stop-sec stop-usec
))
903 (when (and (zerop to-sec
) (not (plusp to-usec
)))
904 (setf status
:timeout
)))
905 ;; If we ran into deadline, try to get the mutex before
906 ;; signaling. If we don't unwind it will look like a normal
907 ;; return from user perspective.
908 (when (and (eq :timeout status
) deadlinep
)
909 (let ((got-it (%try-mutex mutex me
)))
910 (allow-with-interrupts
913 (return-from %condition-wait t
))
915 ;; The deadline may have changed.
916 (setf (values to-sec to-usec stop-sec stop-usec deadlinep
)
917 (decode-timeout timeout
))
918 (setf status
:ok
))))))
919 ;; Re-acquire the mutex for normal return.
920 (when (eq :ok status
)
921 (unless (or (%try-mutex mutex me
)
922 (allow-with-interrupts
923 (%wait-for-mutex mutex me timeout
925 stop-sec stop-usec deadlinep
)))
926 (setf status
:timeout
)))))
927 ;; Determine actual return value. :ok means (potentially
928 ;; spurious) wakeup => T. :timeout => NIL.
932 (multiple-value-bind (sec usec
)
933 (sb!impl
::relative-decoded-times stop-sec stop-usec
)
939 ;; The only case we return normally without re-acquiring
940 ;; the mutex is when there is a :TIMEOUT that runs out.
941 (bug "%CONDITION-WAIT: invalid status on normal return: ~S" status
))))))
942 (declaim (notinline %condition-wait
))
944 (defun condition-wait (queue mutex
&key timeout
)
946 "Atomically release MUTEX and start waiting on QUEUE for till another thread
947 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
948 queue, at which point we re-acquire MUTEX and return T.
950 Spurious wakeups are possible.
952 If TIMEOUT is given, it is the maximum number of seconds to wait, including
953 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
954 wakeup and re-acquisition do not occur within the given time, returns NIL
955 without re-acquiring the mutex.
957 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
959 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
960 occurred the correct way to write code that uses CONDITION-WAIT is to loop
961 around the call, checking the the associated data:
964 (defvar *queue* (make-waitqueue))
965 (defvar *lock* (make-mutex))
968 (defun pop-data (&optional timeout)
971 do (or (condition-wait *queue* *lock* :timeout timeout)
972 ;; Lock not held, must unwind without touching *data*.
973 (return-from pop-data nil)))
977 (defun push-data (data)
980 (condition-notify *queue*)))
983 (locally (declare (inline %condition-wait
))
984 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep
)
985 (decode-timeout timeout
)
987 (%condition-wait queue mutex timeout
988 to-sec to-usec stop-sec stop-usec deadlinep
)))))
990 (defun condition-notify (queue &optional
(n 1))
992 "Notify N threads waiting on QUEUE.
994 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
995 must be held by this thread during this call."
997 (declare (ignore queue n
))
999 (error "Not supported in unithread builds.")
1001 (declare (type (and fixnum
(integer 1)) n
))
1002 (/show0
"Entering CONDITION-NOTIFY")
1006 (with-cas-lock ((waitqueue-%owner queue
))
1007 (%waitqueue-wakeup queue n
))
1010 ;; No problem if >1 thread notifies during the comment in condition-wait:
1011 ;; as long as the value in queue-data isn't the waiting thread's id, it
1012 ;; matters not what it is -- using the queue object itself is handy.
1014 ;; XXX we should do something to ensure that the result of this setf
1015 ;; is visible to all CPUs.
1017 ;; ^-- surely futex_wake() involves a memory barrier?
1018 (setf (waitqueue-token queue
) queue
)
1019 (with-pinned-objects (queue)
1020 (futex-wake (waitqueue-token-address queue
) n
)))))
1022 (defun condition-broadcast (queue)
1024 "Notify all threads waiting on QUEUE.
1026 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
1027 must be held by this thread during this call."
1028 (condition-notify queue
1029 ;; On a 64-bit platform truncating M-P-F to an int
1030 ;; results in -1, which wakes up only one thread.
1032 most-positive-fixnum
)))
1037 (defstruct (semaphore (:constructor make-semaphore
1038 (&key name
((:count %count
) 0))))
1040 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
1041 should be considered an implementation detail, and may change in the
1043 (name nil
:type
(or null thread-name
))
1044 (%count
0 :type
(integer 0))
1045 (waitcount 0 :type sb
!vm
:word
)
1046 (mutex (make-mutex))
1047 (queue (make-waitqueue)))
1050 (setf (fdocumentation 'semaphore-name
'function
)
1051 "The name of the semaphore INSTANCE. Setfable."
1052 (fdocumentation 'make-semaphore
'function
)
1053 "Create a semaphore with the supplied COUNT and NAME.")
1055 (defstruct (semaphore-notification (:constructor make-semaphore-notification
())
1058 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
1059 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
1060 multiple threads are using the same notification object in parallel."
1061 (%status nil
:type boolean
))
1064 (setf (fdocumentation 'make-semaphore-notification
'function
)
1065 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
1068 (declaim (inline semaphore-notification-status
))
1069 (defun semaphore-notification-status (semaphore-notification)
1071 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
1072 SEMAPHORE-NOTIFICATION has succeeded since the notification object was created
1075 (semaphore-notification-%status semaphore-notification
))
1077 (declaim (inline clear-semaphore-notification
))
1078 (defun clear-semaphore-notification (semaphore-notification)
1080 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
1081 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
1083 (setf (semaphore-notification-%status semaphore-notification
) nil
)))
1085 (declaim (inline semaphore-count
))
1086 (defun semaphore-count (instance)
1088 "Returns the current count of the semaphore INSTANCE."
1090 (semaphore-%count instance
))
1092 (declaim (ftype (sfunction (semaphore (integer 1) (or boolean real
)
1093 (or null semaphore-notification
) symbol
)
1095 %decrement-semaphore
))
1096 (defun %decrement-semaphore
(semaphore n wait notification context
)
1097 (when (and notification
(semaphore-notification-status notification
))
1098 (with-simple-restart (continue "Clear notification status and continue.")
1099 (error "~@<Semaphore notification object status not cleared on ~
1100 entry to ~S on ~S.~:@>"
1102 (clear-semaphore-notification notification
))
1104 ;; A more direct implementation based directly on futexes should be
1107 ;; We need to disable interrupts so that we don't forget to
1108 ;; decrement the waitcount (which would happen if an asynch
1109 ;; interrupt should catch us on our way out from the loop.)
1111 ;; FIXME: No timeout on initial mutex acquisition.
1112 (with-system-mutex ((semaphore-mutex semaphore
) :allow-with-interrupts t
)
1113 (flet ((success (new-count)
1115 (setf (semaphore-%count semaphore
) new-count
)
1117 (setf (semaphore-notification-%status notification
) t
)))))
1118 ;; Quick check: can we decrement right away? If not, return or
1119 ;; enter the wait loop.
1121 ((let ((old-count (semaphore-%count semaphore
)))
1122 (when (>= old-count n
)
1123 (success (- old-count n
)))))
1128 (binding* ((old-count nil
)
1129 (timeout (when (realp wait
) wait
))
1130 ((to-sec to-usec stop-sec stop-usec deadlinep
)
1132 (decode-timeout timeout
))))
1133 ;; Need to use ATOMIC-INCF despite the lock, because
1134 ;; on our way out from here we might not be locked
1135 ;; anymore -- so another thread might be tweaking this
1136 ;; in parallel using ATOMIC-DECF. No danger over
1137 ;; overflow, since there it at most one increment per
1138 ;; thread waiting on the semaphore.
1139 (sb!ext
:atomic-incf
(semaphore-waitcount semaphore
))
1140 (loop until
(>= (setf old-count
(semaphore-%count semaphore
)) n
)
1141 do
(multiple-value-bind (wakeup-p remaining-sec remaining-usec
)
1143 (semaphore-queue semaphore
)
1144 (semaphore-mutex semaphore
)
1145 timeout to-sec to-usec stop-sec stop-usec deadlinep
)
1146 (when (or (not wakeup-p
)
1147 (and (eql remaining-sec
0)
1148 (eql remaining-usec
0)))
1149 (return-from %decrement-semaphore nil
)) ; timeout
1151 (setf to-sec remaining-sec
1152 to-usec remaining-usec
))))
1153 (success (- old-count n
)))
1154 ;; Need to use ATOMIC-DECF as we may unwind without the
1156 (sb!ext
:atomic-decf
(semaphore-waitcount semaphore
))))))))
1158 (declaim (ftype (sfunction (semaphore &key
1160 (:timeout
(real (0)))
1161 (:notification semaphore-notification
))
1162 (or null
(integer 0)))
1164 (defun wait-on-semaphore (semaphore &key
(n 1) timeout notification
)
1166 "Decrement the count of SEMAPHORE by N if the count would not be negative.
1168 Else blocks until the semaphore can be decremented. Returns the new count of
1169 SEMAPHORE on success.
1171 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
1172 cannot be decremented in that time, returns NIL without decrementing the
1175 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
1176 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
1177 decrements the count, the status is set to T."
1178 (%decrement-semaphore
1179 semaphore n
(or timeout t
) notification
'wait-on-semaphore
))
1181 (declaim (ftype (sfunction (semaphore &optional
1182 (integer 1) semaphore-notification
)
1183 (or null
(integer 0)))
1185 (defun try-semaphore (semaphore &optional
(n 1) notification
)
1187 "Try to decrement the count of SEMAPHORE by N. If the count were to
1188 become negative, punt and return NIL, otherwise return the new count of
1191 If NOTIFICATION is given it must be a semaphore notification object
1192 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1193 the status is set to T."
1194 (%decrement-semaphore semaphore n nil notification
'try-semaphore
))
1196 (defun signal-semaphore (semaphore &optional
(n 1))
1198 "Increment the count of SEMAPHORE by N. If there are threads waiting
1199 on this semaphore, then N of them is woken up."
1200 (declare (type (integer 1) n
))
1201 ;; Need to disable interrupts so that we don't lose a wakeup after
1202 ;; we have incremented the count.
1203 (with-system-mutex ((semaphore-mutex semaphore
) :allow-with-interrupts t
)
1204 (let ((waitcount (semaphore-waitcount semaphore
))
1205 (count (incf (semaphore-%count semaphore
) n
)))
1206 (when (plusp waitcount
)
1207 (condition-notify (semaphore-queue semaphore
) (min waitcount count
))))))
1210 ;;;; Job control, independent listeners
1213 (lock (make-mutex :name
"session lock"))
1215 (interactive-threads nil
)
1216 (interactive-threads-queue (make-waitqueue)))
1218 (defvar *session
* nil
)
1220 ;;; The debugger itself tries to acquire the session lock, don't let
1221 ;;; funny situations (like getting a sigint while holding the session
1222 ;;; lock) occur. At the same time we need to allow interrupts while
1223 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1224 ;;; be interruptible.
1226 ;;; Take care: we sometimes need to obtain the session lock while
1227 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1228 ;;; _after_ getting a session lock! (Deadlock risk.)
1230 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1232 (defmacro with-session-lock
((session) &body body
)
1233 `(with-system-mutex ((session-lock ,session
) :allow-with-interrupts t
)
1236 (defun new-session ()
1237 (make-session :threads
(list *current-thread
*)
1238 :interactive-threads
(list *current-thread
*)))
1240 (defun init-job-control ()
1241 (/show0
"Entering INIT-JOB-CONTROL")
1242 (setf *session
* (new-session))
1243 (/show0
"Exiting INIT-JOB-CONTROL"))
1245 (defun %delete-thread-from-session
(thread session
)
1246 (with-session-lock (session)
1247 (setf (session-threads session
)
1248 ;; DELQ never conses, but DELETE does. (FIXME)
1249 (delq thread
(session-threads session
))
1250 (session-interactive-threads session
)
1251 (delq thread
(session-interactive-threads session
)))))
1253 (defun call-with-new-session (fn)
1254 (%delete-thread-from-session
*current-thread
* *session
*)
1255 (let ((*session
* (new-session)))
1258 (defmacro with-new-session
(args &body forms
)
1259 (declare (ignore args
)) ;for extensibility
1260 (sb!int
:with-unique-names
(fb-name)
1261 `(labels ((,fb-name
() ,@forms
))
1262 (call-with-new-session (function ,fb-name
)))))
1264 ;;; Remove thread from its session, if it has one.
1266 (defun handle-thread-exit (thread)
1267 (/show0
"HANDLING THREAD EXIT")
1268 (when *exit-in-process
*
1270 ;; Lisp-side cleanup
1271 (with-all-threads-lock
1272 (setf (thread-%alive-p thread
) nil
)
1273 (setf (thread-os-thread thread
) 0)
1274 (setq *all-threads
* (delq thread
*all-threads
*))
1276 (%delete-thread-from-session thread
*session
*))))
1278 (defun %exit-other-threads
()
1279 ;; Grabbing this lock prevents new threads from
1280 ;; being spawned, and guarantees that *ALL-THREADS*
1282 (with-deadline (:seconds nil
:override t
)
1283 (grab-mutex *make-thread-lock
*)
1284 (let ((timeout sb
!ext
:*exit-timeout
*)
1285 (code *exit-in-process
*)
1286 (current *current-thread
*)
1289 (dolist (thread (list-all-threads))
1290 (cond ((eq thread current
))
1291 ((main-thread-p thread
)
1296 (terminate-thread thread
)
1297 (push thread joinees
))
1298 (interrupt-thread-error ())))))
1299 (with-progressive-timeout (time-left :seconds timeout
)
1300 (dolist (thread joinees
)
1301 (join-thread thread
:default t
:timeout
(time-left)))
1302 ;; Need to defer till others have joined, because when main
1303 ;; thread exits, we're gone. Can't use TERMINATE-THREAD -- would
1304 ;; get the exit code wrong.
1310 (setf *exit-in-process
* (list code
))
1311 (throw 'sb
!impl
::%end-of-the-world t
)))
1312 (interrupt-thread-error ()))
1313 ;; Normally this never finishes, as once the main-thread unwinds we
1314 ;; exit with the right code, but if times out before that happens,
1315 ;; we will exit after returning -- or rathe racing the main thread
1316 ;; to calling OS-EXIT.
1317 (join-thread main
:default t
:timeout
(time-left)))))))
1319 (defun terminate-session ()
1321 "Kill all threads in session except for this one. Does nothing if current
1322 thread is not the foreground thread."
1323 ;; FIXME: threads created in other threads may escape termination
1325 (with-session-lock (*session
*)
1326 (and (eq *current-thread
*
1327 (car (session-interactive-threads *session
*)))
1328 (session-threads *session
*)))))
1329 ;; do the kill after dropping the mutex; unwind forms in dying
1330 ;; threads may want to do session things
1331 (dolist (thread to-kill
)
1332 (unless (eq thread
*current-thread
*)
1333 ;; terminate the thread but don't be surprised if it has
1334 ;; exited in the meantime
1335 (handler-case (terminate-thread thread
)
1336 (interrupt-thread-error ()))))))
1338 ;;; called from top of invoke-debugger
1339 (defun debugger-wait-until-foreground-thread (stream)
1341 "Returns T if thread had been running in background, NIL if it was
1343 (declare (ignore stream
))
1347 (with-session-lock (*session
*)
1348 (not (member *current-thread
*
1349 (session-interactive-threads *session
*))))
1352 (defun get-foreground ()
1355 (let ((was-foreground t
))
1357 (/show0
"Looping in GET-FOREGROUND")
1358 (with-session-lock (*session
*)
1359 (let ((int-t (session-interactive-threads *session
*)))
1360 (when (eq (car int-t
) *current-thread
*)
1361 (unless was-foreground
1362 (format *query-io
* "Resuming thread ~A~%" *current-thread
*))
1363 (return-from get-foreground t
))
1364 (setf was-foreground nil
)
1365 (unless (member *current-thread
* int-t
)
1366 (setf (cdr (last int-t
))
1367 (list *current-thread
*)))
1369 (session-interactive-threads-queue *session
*)
1370 (session-lock *session
*)))))))
1372 (defun release-foreground (&optional next
)
1374 "Background this thread. If NEXT is supplied, arrange for it to
1375 have the foreground next."
1376 #!-sb-thread
(declare (ignore next
))
1379 (with-session-lock (*session
*)
1380 (when (rest (session-interactive-threads *session
*))
1381 (setf (session-interactive-threads *session
*)
1382 (delete *current-thread
* (session-interactive-threads *session
*))))
1384 (setf (session-interactive-threads *session
*)
1386 (delete next
(session-interactive-threads *session
*)))))
1387 (condition-broadcast (session-interactive-threads-queue *session
*))))
1389 (defun interactive-threads (&optional
(session *session
*))
1391 "Return the interactive threads of SESSION defaulting to the current
1393 (session-interactive-threads session
))
1395 (defun foreground-thread (&optional
(session *session
*))
1397 "Return the foreground thread of SESSION defaulting to the current
1399 (first (interactive-threads session
)))
1401 (defun make-listener-thread (tty-name)
1402 (assert (probe-file tty-name
))
1403 (let* ((in (sb!unix
:unix-open
(namestring tty-name
) sb
!unix
:o_rdwr
#o666
))
1404 (out (sb!unix
:unix-dup in
))
1405 (err (sb!unix
:unix-dup in
)))
1406 (labels ((thread-repl ()
1407 (sb!unix
::unix-setsid
)
1408 (let* ((sb!impl
::*stdin
*
1409 (make-fd-stream in
:input t
:buffering
:line
1412 (make-fd-stream out
:output t
:buffering
:line
1415 (make-fd-stream err
:output t
:buffering
:line
1418 (make-fd-stream err
:input t
:output t
1421 (sb!impl
::*descriptor-handlers
* nil
))
1422 (with-new-session ()
1424 (sb!impl
::toplevel-repl nil
)
1425 (sb!int
:flush-standard-output-streams
))))))
1426 (make-thread #'thread-repl
))))
1432 (defun initial-thread-function-trampoline
1433 (thread setup-sem real-function thread-list arguments arg1 arg2 arg3
)
1434 ;; In time we'll move some of the binding presently done in C here
1437 ;; KLUDGE: Here we have a magic list of variables that are not
1438 ;; thread-safe for one reason or another. As people report problems
1439 ;; with the thread safety of certain variables, (e.g. "*print-case* in
1440 ;; multiple threads broken", sbcl-devel 2006-07-14), we add a few more
1441 ;; bindings here. The Right Thing is probably some variant of
1442 ;; Allegro's *cl-default-special-bindings*, as that is at least
1443 ;; accessible to users to secure their own libraries.
1444 ;; --njf, 2006-07-15
1446 ;; As it is, this lambda must not cons until we are ready to run
1447 ;; GC. Be very careful.
1448 (let* ((*current-thread
* thread
)
1449 (*restart-clusters
* nil
)
1450 (*handler-clusters
* sb
!kernel
::**initial-handler-clusters
**)
1451 (*exit-in-process
* nil
)
1452 (sb!impl
::*deadline
* nil
)
1453 (sb!impl
::*deadline-seconds
* nil
)
1454 (sb!impl
::*step-out
* nil
)
1455 ;; internal reader variables
1456 (sb!impl
::*token-buf-pool
* nil
)
1457 ;; internal printer variables
1458 (sb!impl
::*previous-case
* nil
)
1459 (sb!impl
::*previous-readtable-case
* nil
)
1460 (sb!impl
::*internal-symbol-output-fun
* #'error
)
1461 (sb!impl
::*ignored-package-locks
* :invalid
)
1462 (sb!impl
::*descriptor-handlers
* nil
)) ; serve-event
1463 (declare (inline make-restart
)) ;; to allow DX-allocation
1465 (setf sb
!vm
:*alloc-signal
* *default-alloc-signal
*)
1466 (setf (thread-os-thread thread
) (current-thread-os-thread))
1467 (with-mutex ((thread-result-lock thread
))
1468 ;; Normally the list is allocated in the parent thread to
1469 ;; avoid consing in a nascent thread.
1471 (let* ((thread-list (or thread-list
1472 (list thread thread
)))
1473 (session-cons (cdr thread-list
)))
1474 (with-all-threads-lock
1475 (setf (cdr thread-list
) *all-threads
*
1476 *all-threads
* thread-list
))
1477 (let ((session *session
*))
1478 (with-session-lock (session)
1479 (setf (cdr session-cons
) (session-threads session
)
1480 (session-threads session
) session-cons
))))
1481 (setf (thread-%alive-p thread
) t
)
1484 (signal-semaphore setup-sem
)
1485 ;; setup-sem was dx-allocated, set it to NIL so that the
1486 ;; backtrace doesn't get confused
1487 (setf setup-sem nil
))
1489 ;; Using handling-end-of-the-world would be a bit tricky
1490 ;; due to other catches and interrupts, so we essentially
1491 ;; re-implement it here. Once and only once more.
1492 (catch 'sb
!impl
::toplevel-catcher
1493 (catch 'sb
!impl
::%end-of-the-world
1494 (catch '%abort-thread
1495 (restart-bind ((abort
1497 (throw '%abort-thread nil
))
1500 (format stream
"~@<abort thread (~a)~@:>"
1501 *current-thread
*))))
1504 (with-local-interrupts
1505 (setf *gc-inhibit
* nil
) ;for foreign callbacks
1506 (sb!unix
::unblock-deferrable-signals
)
1507 (setf (thread-result thread
)
1509 (multiple-value-list
1511 (catch '%return-from-thread
1512 (if (listp arguments
)
1513 (apply real-function arguments
)
1514 (funcall real-function arg1 arg2 arg3
)))
1515 (when *exit-in-process
*
1516 (sb!impl
::call-exit-hooks
))))
1518 (sb!kernel
::gc-safepoint
))))
1519 ;; we're going down, can't handle interrupts
1520 ;; sanely anymore. gc remains enabled.
1521 (block-deferrable-signals)
1522 ;; we don't want to run interrupts in a dead
1523 ;; thread when we leave without-interrupts.
1524 ;; this potentially causes important
1525 ;; interupts to be lost: sigint comes to
1527 (setq *interrupt-pending
* nil
)
1529 (setq *thruption-pending
* nil
)
1530 (handle-thread-exit thread
)))))))))
1533 (defun make-thread (function &key name arguments ephemeral
)
1535 "Create a new thread of NAME that runs FUNCTION with the argument
1536 list designator provided (defaults to no argument). Thread exits when
1537 the function returns. The return values of FUNCTION are kept around
1538 and can be retrieved by JOIN-THREAD.
1540 Invoking the initial ABORT restart established by MAKE-THREAD
1541 terminates the thread.
1543 See also: RETURN-FROM-THREAD, ABORT-THREAD."
1544 #!-sb-thread
(declare (ignore function name arguments ephemeral
))
1545 #!-sb-thread
(error "Not supported in unithread builds.")
1546 #!+sb-thread
(assert (or (atom arguments
)
1547 (null (cdr (last arguments
))))
1549 "Argument passed to ~S, ~S, is an improper list."
1550 'make-thread arguments
)
1552 (let ((thread (%make-thread
:name name
:%ephemeral-p ephemeral
)))
1553 (declare (inline make-semaphore
1556 (let* ((setup-sem (make-semaphore :name
"Thread setup semaphore"))
1557 (real-function (coerce function
'function
))
1558 (arguments (ensure-list arguments
))
1559 #!+(or win32 darwin
)
1560 (fp-modes (dpb 0 sb
!vm
::float-sticky-bits
;; clear accrued bits
1561 (sb!vm
:floating-point-modes
)))
1562 ;; Allocate in the parent
1563 (thread-list (list thread thread
)))
1564 (declare (dynamic-extent setup-sem
))
1565 (dx-flet ((initial-thread-function ()
1566 ;; Inherit parent thread's FP modes
1567 #!+(or win32 darwin
)
1568 (setf (sb!vm
:floating-point-modes
) fp-modes
)
1569 ;; As it is, this lambda must not cons until we are
1570 ;; ready to run GC. Be very careful.
1571 (initial-thread-function-trampoline
1572 thread setup-sem real-function thread-list
1573 arguments nil nil nil
)))
1574 ;; If the starting thread is stopped for gc before it signals
1575 ;; the semaphore then we'd be stuck.
1576 (assert (not *gc-inhibit
*))
1577 ;; Keep INITIAL-FUNCTION in the dynamic extent until the child
1578 ;; thread is initialized properly. Wrap the whole thing in
1579 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to
1581 (with-system-mutex (*make-thread-lock
*)
1583 (%create-thread
(get-lisp-obj-address #'initial-thread-function
)))
1585 (wait-on-semaphore setup-sem
)))))
1586 (or thread
(error "Could not create a new thread."))))
1588 (defun join-thread (thread &key
(default nil defaultp
) timeout
)
1590 "Suspend current thread until THREAD exits. Return the result values
1591 of the thread function.
1593 If THREAD does not exit within TIMEOUT seconds and DEFAULT is
1594 supplied, return two values: 1) DEFAULT 2) :TIMEOUT. If DEFAULT is not
1595 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-PROBLEM equal
1598 If THREAD does not exit normally (i.e. aborted) and DEFAULT is
1599 supplied, return two values: 1) DEFAULT 2) :ABORT. If DEFAULT is not
1600 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-PROBLEM equal
1603 If THREAD is the current thread, signal a JOIN-THREAD-ERROR with
1604 JOIN-THREAD-PROBLEM equal to :SELF-JOIN.
1606 Trying to join the main thread causes JOIN-THREAD to block until
1607 TIMEOUT occurs or the process exits: when the main thread exits, the
1608 entire process exits.
1610 NOTE: Return convention in case of a timeout is experimental and
1612 (when (eq thread
*current-thread
*)
1613 (error 'join-thread-error
:thread thread
:problem
:self-join
))
1615 (let ((lock (thread-result-lock thread
))
1622 (allow-with-interrupts
1623 ;; Don't use the timeout if the thread is
1624 ;; not alive anymore.
1625 (grab-mutex lock
:timeout
(and (thread-alive-p thread
)
1627 ((listp (thread-result thread
))
1628 (return-from join-thread
1629 (values-list (thread-result thread
))))
1631 (setf problem
:abort
)))
1633 (release-mutex lock
))))
1635 (values default problem
)
1636 (error 'join-thread-error
:thread thread
:problem problem
))))
1638 (defun destroy-thread (thread)
1639 (terminate-thread thread
))
1642 (declaim (sb!ext
:deprecated
1643 :late
("SBCL" "1.2.15")
1644 (function destroy-thread
:replacement terminate-thread
)))
1647 (defun enter-foreign-callback (arg1 arg2 arg3
)
1648 (initial-thread-function-trampoline
1649 (make-foreign-thread :name
"foreign callback")
1650 nil
#'sb
!alien
::enter-alien-callback nil t arg1 arg2 arg3
))
1652 (defmacro with-interruptions-lock
((thread) &body body
)
1653 `(with-system-mutex ((thread-interruptions-lock ,thread
))
1656 ;;; Called from the signal handler.
1657 #!-
(or sb-thruption win32
)
1658 (defun run-interruption ()
1659 (let ((interruption (with-interruptions-lock (*current-thread
*)
1660 (pop (thread-interruptions *current-thread
*)))))
1661 ;; If there is more to do, then resignal and let the normal
1662 ;; interrupt deferral mechanism take care of the rest. From the
1663 ;; OS's point of view the signal we are in the handler for is no
1664 ;; longer pending, so the signal will not be lost.
1665 (when (thread-interruptions *current-thread
*)
1666 (kill-safely (thread-os-thread *current-thread
*) sb
!unix
:sigpipe
))
1668 (funcall interruption
))))
1671 (defun run-interruption ()
1672 (in-interruption () ;the non-thruption code does this in the signal handler
1673 (let ((interruption (with-interruptions-lock (*current-thread
*)
1674 (pop (thread-interruptions *current-thread
*)))))
1676 (funcall interruption
)
1677 ;; I tried implementing this function as an explicit LOOP, because
1678 ;; if we are currently processing the thruption queue, why not do
1679 ;; all of them in one go instead of one-by-one?
1681 ;; I still think LOOPing would be basically the right thing
1682 ;; here. But suppose some interruption unblocked deferrables.
1683 ;; Will the next one be happy with that? The answer is "no", at
1684 ;; least in the sense that there are tests which check that
1685 ;; deferrables are blocked at the beginning of a thruption, and
1686 ;; races that make those tests fail. Whether the tests are
1687 ;; misguided or not, it seems easier/cleaner to loop implicitly
1688 ;; -- and it's also what AK had implemented in the first place.
1690 ;; The implicit loop is achieved by returning to C, but having C
1691 ;; call back to us immediately. The runtime will reset the sigmask
1692 ;; in the mean time.
1694 (setf *thruption-pending
* t
)))))
1696 (defun interrupt-thread (thread function
)
1698 "Interrupt THREAD and make it run FUNCTION.
1700 The interrupt is asynchronous, and can occur anywhere with the exception of
1701 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1703 FUNCTION is called with interrupts disabled, under
1704 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1705 enable interrupts internally, in most cases FUNCTION should either enter
1706 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1707 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1709 When a thread receives multiple interrupts, they are executed in the order
1710 they were sent -- first in, first out.
1712 This means that a great degree of care is required to use INTERRUPT-THREAD
1713 safely and sanely in a production environment. The general recommendation is
1714 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1715 entirely from production environments -- it is simply exceedingly hard to use
1718 With those caveats in mind, what you need to know when using it:
1720 * If calling FUNCTION causes a non-local transfer of control (ie. an
1721 unwind), all normal cleanup forms will be executed.
1723 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1724 it is just as if that had happened due to a regular GO, THROW, or
1725 RETURN-FROM: the interrupted cleanup form and those following it in the
1726 same UNWIND-PROTECT do not get executed.
1728 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1729 frankly an unreasonable expectation for third party libraries, especially
1730 given that asynch-unwind-safety does not compose: a function calling
1731 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1733 This means that in order for an asynch unwind to be safe, the entire
1734 callstack at the point of interruption needs to be asynch-unwind-safe.
1736 * In addition to asynch-unwind-safety you must consider the issue of
1737 reentrancy. INTERRUPT-THREAD can cause function that are never normally
1738 called recursively to be re-entered during their dynamic contour,
1739 which may cause them to misbehave. (Consider binding of special variables,
1740 values of global variables, etc.)
1742 Take together, these two restrict the \"safe\" things to do using
1743 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1744 interactive development use is using it to force entry to debugger to inspect
1745 the state of a thread:
1747 (interrupt-thread thread #'break)
1749 Short version: be careful out there."
1750 #!+(and (not sb-thread
) win32
)
1751 #!+(and (not sb-thread
) win32
)
1752 (declare (ignore thread
))
1753 (with-interrupt-bindings
1754 (with-interrupts (funcall function
)))
1755 #!-
(and (not sb-thread
) win32
)
1756 (let ((os-thread (thread-os-thread thread
)))
1757 (cond ((not os-thread
)
1758 (error 'interrupt-thread-error
:thread thread
))
1760 (with-interruptions-lock (thread)
1761 ;; Append to the end of the interruptions queue. It's
1762 ;; O(N), but it does not hurt to slow interruptors down a
1763 ;; bit when the queue gets long.
1764 (setf (thread-interruptions thread
)
1765 (append (thread-interruptions thread
)
1768 (allow-with-interrupts
1769 (funcall function
))))))))
1770 (when (minusp (wake-thread os-thread
))
1771 (error 'interrupt-thread-error
:thread thread
))))))
1773 (defun terminate-thread (thread)
1775 "Terminate the thread identified by THREAD, by interrupting it and
1776 causing it to call SB-EXT:ABORT-THREAD with :ALLOW-EXIT T.
1778 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that
1779 eg. thread executing
1784 (setf foo (get-foo))
1787 ;; An interrupt occurring inside the cleanup clause
1788 ;; will cause cleanups from the current UNWIND-PROTECT
1790 (release-foo foo))))
1792 might miss calling RELEASE-FOO despite GET-FOO having returned true if
1793 the interrupt occurs inside the cleanup clause, eg. during execution
1796 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need
1797 to use WITHOUT-INTERRUPTS:
1800 (sb-sys:without-interrupts
1803 (setf foo (sb-sys:allow-with-interrupts
1805 (sb-sys:with-local-interrupts
1808 (release-foo foo)))))
1810 Since most libraries using UNWIND-PROTECT do not do this, you should never
1811 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1812 (interrupt-thread thread
(lambda () (abort-thread :allow-exit t
))))
1814 (define-alien-routine "thread_yield" int
)
1817 (setf (fdocumentation 'thread-yield
'function
)
1818 "Yield the processor to other threads.")
1820 ;;; internal use only. If you think you need to use these, either you
1821 ;;; are an SBCL developer, are doing something that you should discuss
1822 ;;; with an SBCL developer first, or are doing something that you
1823 ;;; should probably discuss with a professional psychiatrist first
1826 (defun %thread-sap
(thread)
1827 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t
))))
1828 (target (thread-os-thread thread
)))
1830 (when (sap= thread-sap
(int-sap 0)) (return nil
))
1831 (let ((os-thread (sap-ref-word thread-sap
1832 (* sb
!vm
:n-word-bytes
1833 sb
!vm
::thread-os-thread-slot
))))
1834 (when (= os-thread target
) (return thread-sap
))
1836 (sap-ref-sap thread-sap
(* sb
!vm
:n-word-bytes
1837 sb
!vm
::thread-next-slot
)))))))
1839 (defun %symbol-value-in-thread
(symbol thread
)
1840 ;; Prevent the thread from dying completely while we look for the TLS
1842 (with-all-threads-lock
1843 (if (thread-alive-p thread
)
1844 (let* ((offset (get-lisp-obj-address (symbol-tls-index symbol
)))
1845 (obj (sap-ref-lispobj (%thread-sap thread
) offset
))
1846 (tl-val (get-lisp-obj-address obj
)))
1847 (cond ((zerop offset
)
1848 (values nil
:no-tls-value
))
1849 ((or (eql tl-val sb
!vm
:no-tls-value-marker-widetag
)
1850 (eql tl-val sb
!vm
:unbound-marker-widetag
))
1851 (values nil
:unbound-in-thread
))
1854 (values nil
:thread-dead
))))
1856 (defun %set-symbol-value-in-thread
(symbol thread value
)
1857 (with-pinned-objects (value)
1858 ;; Prevent the thread from dying completely while we look for the TLS
1860 (with-all-threads-lock
1861 (if (thread-alive-p thread
)
1862 (let ((offset (get-lisp-obj-address (symbol-tls-index symbol
))))
1863 (cond ((zerop offset
)
1864 (values nil
:no-tls-value
))
1866 (setf (sap-ref-lispobj (%thread-sap thread
) offset
)
1868 (values value
:ok
))))
1869 (values nil
:thread-dead
)))))
1871 (define-alien-variable tls-index-start unsigned-int
)
1873 ;; Get values from the TLS area of the current thread.
1874 (defun %thread-local-references
()
1875 ;; TLS-INDEX-START is a word number relative to thread base.
1876 ;; *FREE-TLS-INDEX* - which is only manipulated by machine code - is an
1877 ;; offset from thread base to the next usable TLS cell as a raw word
1878 ;; manifesting in Lisp as a fixnum. Convert it from byte number to word
1879 ;; number before using it as the upper bound for the sequential scan.
1880 (loop for index from tls-index-start
1881 ;; On x86-64, mask off the sign bit. It is used as a semaphore.
1882 below
(ash (logand #!+x86-64 most-positive-fixnum
1883 sb
!vm
::*free-tls-index
*)
1884 (+ (- sb
!vm
:word-shift
) sb
!vm
:n-fixnum-tag-bits
))
1885 for obj
= (sb!kernel
:%make-lisp-obj
1886 (sb!sys
:sap-int
(sb!vm
::current-thread-offset-sap index
)))
1887 unless
(or (member (widetag-of obj
)
1888 `(,sb
!vm
:no-tls-value-marker-widetag
1889 ,sb
!vm
:unbound-marker-widetag
))
1890 (typep obj
'(or fixnum character
))
1892 collect obj into seen
1893 finally
(return seen
))))
1895 (defun symbol-value-in-thread (symbol thread
&optional
(errorp t
))
1897 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1900 If the value cannot be retrieved (because the thread has exited or because it
1901 has no local binding for NAME) and ERRORP is true signals an error of type
1902 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1903 NIL, and a secondary value of NIL.
1905 Can also be used with SETF to change the thread-local value of SYMBOL.
1907 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1908 mechanism for inter-thread communication."
1909 (declare (symbol symbol
) (thread thread
))
1911 (multiple-value-bind (res status
) (%symbol-value-in-thread symbol thread
)
1915 (error 'symbol-value-in-thread-error
1918 :info
(list :read status
))
1922 (values (symbol-value symbol
) t
)
1924 (error 'symbol-value-in-thread-error
1927 :info
(list :read
:unbound-in-thread
))
1930 (defun (setf symbol-value-in-thread
) (value symbol thread
&optional
(errorp t
))
1931 (declare (symbol symbol
) (thread thread
))
1933 (multiple-value-bind (res status
) (%set-symbol-value-in-thread symbol thread value
)
1937 (error 'symbol-value-in-thread-error
1940 :info
(list :write status
))
1944 (values (setf (symbol-value symbol
) value
) t
)
1946 (error 'symbol-value-in-thread-error
1949 :info
(list :write
:unbound-in-thread
))
1956 (defun thread-stepping ()
1957 (sap-ref-lispobj (current-thread-sap)
1958 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
)))
1960 (defun (setf thread-stepping
) (value)
1961 (setf (sap-ref-lispobj (current-thread-sap)
1962 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
))