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
)
22 "Runs BODY with interrupts disabled and *CURRENT-THREAD* compare-and-swapped
23 into PLACE instead of NIL. PLACE must be a place acceptable to
24 COMPARE-AND-SWAP, and must initially hold NIL.
26 WITH-CAS-LOCK is suitable mostly when the critical section needing protection
27 is very small, and cost of allocating a separate lock object would be
28 prohibitive. While it is the most lightweight locking constructed offered by
29 SBCL, it is also the least scalable if the section is heavily contested or
32 WITH-CAS-LOCK can be entered recursively."
34 (%with-cas-lock
(,place
) ,@body
)))
36 (defmacro %with-cas-lock
((place) &body body
&environment env
)
37 (with-unique-names (owner self
)
38 (multiple-value-bind (vars vals old new cas-form read-form
)
39 (sb!ext
:get-cas-expansion place env
)
40 `(let* (,@(mapcar #'list vars vals
)
44 (,self
*current-thread
*)
49 (unless (eq ,owner
,self
)
50 (loop until
(loop repeat
100
54 (not (setf ,owner
,cas-form
)))
57 do
(sb!ext
:spin-loop-hint
))
60 (unless (eq ,owner
,self
)
63 (unless (eq ,old
,cas-form
)
64 (bug "Failed to release CAS lock!")))))))))
68 (define-condition thread-error
(error)
69 ((thread :reader thread-error-thread
:initarg
:thread
))
71 "Conditions of type THREAD-ERROR are signalled when thread operations fail.
72 The offending thread is initialized by the :THREAD initialization argument and
73 read by the function THREAD-ERROR-THREAD."))
75 (define-condition simple-thread-error
(thread-error simple-condition
)
78 (define-condition thread-deadlock
(thread-error)
79 ((cycle :initarg
:cycle
:reader thread-deadlock-cycle
))
81 (lambda (condition stream
)
82 (let* ((*print-circle
* t
)
83 (cycle (thread-deadlock-cycle condition
))
85 (format stream
"Deadlock cycle detected:~%")
86 (loop for part
= (pop cycle
)
88 do
(format stream
" ~S~% waited for:~% ~S~% owned by:~%"
91 (format stream
" ~S~%" start
)))))
94 (fdocumentation 'thread-error-thread
'function
)
95 "Return the offending thread that the THREAD-ERROR pertains to.")
97 (define-condition symbol-value-in-thread-error
(cell-error thread-error
)
98 ((info :reader symbol-value-in-thread-error-info
:initarg
:info
))
100 (lambda (condition stream
)
101 (destructuring-bind (op problem
)
102 (symbol-value-in-thread-error-info condition
)
103 (format stream
"Cannot ~(~A~) value of ~S in ~S: ~S"
105 (cell-error-name condition
)
106 (thread-error-thread condition
)
108 (:unbound-in-thread
"the symbol is unbound in thread.")
109 (:no-tls-value
"the symbol has no thread-local value.")
110 (:thread-dead
"the thread has exited.")
111 (:invalid-tls-value
"the thread-local value is not valid."))))))
113 "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
114 the symbol not having a thread-local value, or the target thread having
115 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
116 offending thread using THREAD-ERROR-THREAD."))
118 (define-condition join-thread-error
(thread-error)
119 ((problem :initarg
:problem
:reader join-thread-problem
))
120 (:report
(lambda (c s
)
121 (ecase (join-thread-problem c
)
123 (format s
"Joining thread failed: thread ~A ~
124 did not return normally."
125 (thread-error-thread c
)))
127 (format s
"Joining thread timed out: thread ~A ~
128 did not exit in time."
129 (thread-error-thread c
)))
131 (format s
"In thread ~A, attempt to join the current ~
133 (thread-error-thread c
))))))
135 "Signalled when joining a thread fails due to abnormal exit of the thread
136 to be joined. The offending thread can be accessed using
137 THREAD-ERROR-THREAD."))
139 (define-deprecated-function :late
"1.0.29.17" join-thread-error-thread thread-error-thread
141 (thread-error-thread condition
))
143 (define-condition interrupt-thread-error
(thread-error) ()
144 (:report
(lambda (c s
)
145 (format s
"Interrupt thread failed: thread ~A has exited."
146 (thread-error-thread c
))))
148 "Signalled when interrupting a thread fails because the thread has already
149 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
151 (define-deprecated-function :late
"1.0.29.17" interrupt-thread-error-thread thread-error-thread
153 (thread-error-thread condition
))
155 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
156 ;;; necessary because threads are only supported with the conservative
157 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
158 ;;; are treated as references.
161 (fdocumentation 'thread-name
'function
)
162 "Name of the thread. Can be assigned to using SETF. Thread names can be
163 arbitrary printable objects, and need not be unique.")
165 (defmethod print-object ((thread thread
) stream
)
166 (print-unreadable-object (thread stream
:type t
:identity t
)
167 (let* ((cookie (list thread
))
168 (info (if (thread-alive-p thread
)
171 (join-thread thread
:default cookie
))))
172 (state (if (eq :running info
)
175 (thread-waiting-for thread
))))
178 (list "waiting on:" (cdr thing
)
179 "timeout: " (car thing
)))
183 (list "waiting on:" thing
))))
184 (if (eq cookie
(car info
))
187 (values (when (eq :finished state
)
191 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
197 (defun print-lock (lock name owner stream
)
198 (let ((*print-circle
* t
))
199 (print-unreadable-object (lock stream
:type t
:identity
(not name
))
201 (format stream
"~@[~S ~]~2I~_owner: ~S" name owner
)
202 (format stream
"~@[~S ~](free)" name
)))))
204 (defmethod print-object ((mutex mutex
) stream
)
205 (print-lock mutex
(mutex-name mutex
) (mutex-owner mutex
) stream
))
207 (defun thread-alive-p (thread)
208 "Return T if THREAD is still alive. Note that the return value is
209 potentially stale even before the function returns, as the thread may exit at
211 (thread-%alive-p thread
))
213 ;; NB: ephemeral threads must terminate strictly before the test of NTHREADS>1
214 ;; in DEINIT, i.e. this is not a promise that the thread will terminate
215 ;; just-in-time for the final call out to save, but rather by an earlier time.
216 (defun thread-ephemeral-p (thread)
217 "Return T if THREAD is `ephemeral', which indicates that this thread is
218 used by SBCL for internal purposes, and specifically that our runtime knows how
219 to terminate this thread cleanly prior to core file saving without signalling
220 an error in that case."
221 (thread-%ephemeral-p thread
))
223 ;; A thread is eligible for gc iff it has finished and there are no
224 ;; more references to it. This list is supposed to keep a reference to
225 ;; all running threads.
226 (sb!ext
:define-load-time-global
*all-threads
* ())
227 (sb!ext
:define-load-time-global
*all-threads-lock
* (make-mutex :name
"all threads lock"))
229 (defvar *default-alloc-signal
* nil
)
231 (defmacro with-all-threads-lock
(&body body
)
232 `(with-system-mutex (*all-threads-lock
*)
235 (defun list-all-threads ()
236 "Return a list of the live threads. Note that the return value is
237 potentially stale even before the function returns, as new threads may be
238 created and old ones may exit at any time."
239 (with-all-threads-lock
240 (copy-list *all-threads
*)))
242 ;;; used by debug-int.lisp to access interrupt contexts
244 ;;; The two uses immediately below of (unsigned-byte 27) are arbitrary,
245 ;;; as a more reasonable type restriction is an integer from 0 to
246 ;;; (+ (primitive-object-size
247 ;;; (find 'thread *primitive-objects* :key #'primitive-object-name))
248 ;;; MAX-INTERRUPTS) ; defined only for C in 'interrupt.h'
250 ;;; The x86 32-bit port is helped slightly by having a stricter constraint
251 ;;; than the (unsigned-byte 32) from its DEFKNOWN of this function.
252 ;;; Ideally a single defknown would work for any backend because the thread
253 ;;; structure is, after all, defined in the generic objdefs. But the VM needs
254 ;;; the defknown before the VOP, and this file comes too late, so we'd
255 ;;; need to pick some other place - maybe 'thread.lisp'?
257 #!-
(or sb-fluid sb-thread
) (declaim (inline sb
!vm
::current-thread-offset-sap
))
259 (defun sb!vm
::current-thread-offset-sap
(n)
260 (declare (type (unsigned-byte 27) n
))
261 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t
)))
262 (* n sb
!vm
:n-word-bytes
)))
265 (defun sb!vm
::current-thread-offset-sap
(n)
266 (declare (type (unsigned-byte 27) n
))
267 (sb!vm
::current-thread-offset-sap n
))
269 (declaim (inline current-thread-sap
))
270 (defun current-thread-sap ()
272 (sb!vm
::current-thread-offset-sap sb
!vm
::thread-this-slot
)
276 (declaim (inline current-thread-os-thread
))
277 (defun current-thread-os-thread ()
279 (sap-int (sb!vm
::current-thread-offset-sap sb
!vm
::thread-os-thread-slot
))
283 (sb!ext
:define-load-time-global
*initial-thread
* nil
)
284 (sb!ext
:define-load-time-global
*make-thread-lock
* nil
)
286 (defun init-initial-thread ()
287 (/show0
"Entering INIT-INITIAL-THREAD")
288 (setf sb
!impl
::*exit-lock
* (make-mutex :name
"Exit Lock")
289 *make-thread-lock
* (make-mutex :name
"Make-Thread Lock"))
290 (let ((thread (%make-thread
:name
"main thread"
292 (setf (thread-os-thread thread
) (current-thread-os-thread)
293 (thread-primitive-thread thread
) (sap-int (current-thread-sap))
294 *initial-thread
* thread
295 *current-thread
* thread
)
296 (grab-mutex (thread-result-lock *initial-thread
*))
297 ;; Either *all-threads* is empty or it contains exactly one thread
298 ;; in case we are in reinit since saving core with multiple
299 ;; threads doesn't work.
300 (setq *all-threads
* (list thread
))))
302 (defun main-thread ()
303 "Returns the main thread of the process."
306 (defun main-thread-p (&optional
(thread *current-thread
*))
307 "True if THREAD, defaulting to current thread, is the main thread of the process."
308 (eq thread
*initial-thread
*))
310 (defmacro return-from-thread
(values-form &key allow-exit
)
311 "Unwinds from and terminates the current thread, with values from
312 VALUES-FORM as the results visible to JOIN-THREAD.
314 If current thread is the main thread of the process (see
315 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
316 terminating the main thread would terminate the entire process. If
317 ALLOW-EXIT is true, returning from the main thread is equivalent to
318 calling SB-EXT:EXIT with :CODE 0 and :ABORT NIL.
320 See also: ABORT-THREAD and SB-EXT:EXIT."
321 `(%return-from-thread
(multiple-value-list ,values-form
) ,allow-exit
))
323 (defun %return-from-thread
(values allow-exit
)
324 (let ((self *current-thread
*))
325 (cond ((main-thread-p self
)
327 (error 'simple-thread-error
328 :format-control
"~@<Tried to return ~S as values from main thread, ~
329 but exit was not allowed.~:@>"
330 :format-arguments
(list values
)
332 (sb!ext
:exit
:code
0))
334 (throw '%return-from-thread
(values-list values
))))))
336 (defun abort-thread (&key allow-exit
)
337 "Unwinds from and terminates the current thread abnormally, causing
338 JOIN-THREAD on current thread to signal an error unless a
339 default-value is provided.
341 If current thread is the main thread of the process (see
342 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
343 terminating the main thread would terminate the entire process. If
344 ALLOW-EXIT is true, aborting the main thread is equivalent to calling
345 SB-EXT:EXIT code 1 and :ABORT NIL.
347 Invoking the initial ABORT restart established by MAKE-THREAD is
348 equivalent to calling ABORT-THREAD in other than main threads.
349 However, whereas ABORT restart may be rebound, ABORT-THREAD always
350 unwinds the entire thread. (Behaviour of the initial ABORT restart for
351 main thread depends on the :TOPLEVEL argument to
352 SB-EXT:SAVE-LISP-AND-DIE.)
354 See also: RETURN-FROM-THREAD and SB-EXT:EXIT."
355 (let ((self *current-thread
*))
356 (cond ((main-thread-p self
)
358 (error 'simple-thread-error
359 :format-control
"~@<Tried to abort initial thread, but ~
360 exit was not allowed.~:@>"))
361 (sb!ext
:exit
:code
1))
363 ;; We /could/ use TOPLEVEL-CATCHER or %END-OF-THE-WORLD as well, but
364 ;; this seems tidier. Those to are a bit too overloaded already.
365 (throw '%abort-thread t
)))))
368 ;;;; Aliens, low level stuff
370 (define-alien-routine "kill_safely"
372 (os-thread #!-alpha unsigned
#!+alpha unsigned-int
)
375 (define-alien-routine "wake_thread"
377 (os-thread unsigned
))
381 ;; FIXME it would be good to define what a thread id is or isn't
382 ;; (our current assumption is that it's a fixnum). It so happens
383 ;; that on Linux it's a pid, but it might not be on posix thread
385 (define-alien-routine ("create_thread" %create-thread
)
386 unsigned
(lisp-fun-address unsigned
))
388 (declaim (inline %block-deferrable-signals
))
389 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals
)
394 (defun block-deferrable-signals ()
395 (%block-deferrable-signals
0 0))
399 (declaim (inline futex-wait %futex-wait futex-wake
))
401 (define-alien-routine ("futex_wait" %futex-wait
) int
402 (word unsigned
) (old-value unsigned
)
403 (to-sec long
) (to-usec unsigned-long
))
405 (defun futex-wait (word old to-sec to-usec
)
407 (%futex-wait word old to-sec to-usec
)))
409 (define-alien-routine "futex_wake"
410 int
(word unsigned
) (n unsigned-long
))))
412 (defmacro with-deadlocks
((thread lock
&optional
(timeout nil timeoutp
)) &body forms
)
413 (with-unique-names (n-thread n-lock new n-timeout
)
414 `(let* ((,n-thread
,thread
)
416 (,n-timeout
,(when timeoutp
417 `(or ,timeout sb
!impl
::*deadline
*)))
419 ;; Using CONS tells the rest of the system there's a
420 ;; timeout in place, so it isn't considered a deadlock.
421 (cons ,n-timeout
,n-lock
)
423 (declare (dynamic-extent ,new
))
424 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
425 ;; in places where interrupts should already be disabled.
428 (setf (thread-waiting-for ,n-thread
) ,new
)
431 ;; Interrupt handlers and GC save and restore any
432 ;; previous wait marks using WITHOUT-DEADLOCKS below.
433 (setf (thread-waiting-for ,n-thread
) nil
)
434 (barrier (:write
))))))
438 (setf (fdocumentation 'make-mutex
'function
)
440 (fdocumentation 'mutex-name
'function
)
441 "The name of the mutex. Setfable.")
443 #!+(and sb-thread sb-futex
)
445 (locally (declare (sb!ext
:muffle-conditions sb
!ext
:compiler-note
))
446 (define-structure-slot-addressor mutex-state-address
449 ;; Important: current code assumes these are fixnums or other
450 ;; lisp objects that don't need pinning.
451 (defconstant +lock-free
+ 0)
452 (defconstant +lock-taken
+ 1)
453 (defconstant +lock-contested
+ 2))
455 (defun mutex-owner (mutex)
456 "Current owner of the mutex, NIL if the mutex is free. Naturally,
457 this is racy by design (another thread may acquire the mutex after
458 this function returns), it is intended for informative purposes. For
459 testing whether the current thread is holding a mutex see
461 ;; Make sure to get the current value.
462 (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil nil
))
464 (sb!ext
:defglobal
**deadlock-lock
** nil
)
466 #!+(or (not sb-thread
) sb-futex
)
467 (defstruct (waitqueue (:copier nil
) (:constructor make-waitqueue
(&key name
)))
469 (name nil
:type
(or null thread-name
))
470 #!+(and sb-thread sb-futex
)
473 #!+(and sb-thread
(not sb-futex
))
474 (defstruct (waitqueue (:copier nil
) (:constructor make-waitqueue
(&key name
)))
476 (name nil
:type
(or null thread-name
))
477 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
478 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
479 ;; lock. In most cases this should be uncontested thanks to the mutex --
480 ;; the only case where that might not be true is when CONDITION-WAIT
481 ;; unwinds and %WAITQUEUE-DROP is called.
486 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
487 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
488 (defun check-deadlock ()
489 (let* ((self *current-thread
*)
492 (thread-waiting-for self
))))
493 (labels ((detect-deadlock (lock)
494 (let ((other-thread (mutex-%owner lock
)))
495 (cond ((not other-thread
))
496 ((eq self other-thread
)
498 (with-cas-lock ((symbol-value '**deadlock-lock
**))
499 (prog1 (deadlock-chain self origin
)
500 ;; We're now committed to signaling the
501 ;; error and breaking the deadlock, so
502 ;; mark us as no longer waiting on the
503 ;; lock. This ensures that a single
504 ;; deadlock is reported in only one
505 ;; thread, and that we don't look like
506 ;; we're waiting on the lock when print
507 ;; stuff -- because that may lead to
508 ;; further deadlock checking, in turn
509 ;; possibly leading to a bogus vicious
510 ;; metacycle on PRINT-OBJECT.
511 (setf (thread-waiting-for self
) nil
)))))
512 (error 'thread-deadlock
513 :thread
*current-thread
*
516 (let ((other-lock (progn
518 (thread-waiting-for other-thread
))))
519 ;; If the thread is waiting with a timeout OTHER-LOCK
520 ;; is a cons, and we don't consider it a deadlock -- since
521 ;; it will time out on its own sooner or later.
522 (when (mutex-p other-lock
)
523 (detect-deadlock other-lock
)))))))
524 (deadlock-chain (thread lock
)
525 (let* ((other-thread (mutex-owner lock
))
526 (other-lock (when other-thread
528 (thread-waiting-for other-thread
))))
529 (cond ((not other-thread
)
530 ;; The deadlock is gone -- maybe someone unwound
531 ;; from the same deadlock already?
532 (return-from check-deadlock nil
))
534 ;; There's a timeout -- no deadlock.
535 (return-from check-deadlock nil
))
536 ((waitqueue-p other-lock
)
538 (return-from check-deadlock nil
))
539 ((eq self other-thread
)
541 (list (list thread lock
)))
544 (cons (cons thread lock
)
545 (deadlock-chain other-thread other-lock
))
546 ;; Again, the deadlock is gone?
547 (return-from check-deadlock nil
)))))))
548 ;; Timeout means there is no deadlock
549 (when (mutex-p origin
)
550 (detect-deadlock origin
)
553 (defun %try-mutex
(mutex new-owner
)
554 (declare (type mutex mutex
) (optimize (speed 3)))
556 (let ((old (mutex-%owner mutex
)))
557 (when (eq new-owner old
)
558 (error "Recursive lock attempt ~S." mutex
))
561 (error "Strange deadlock on ~S in an unithreaded build?" mutex
))
562 #!-
(and sb-thread sb-futex
)
564 ;; Don't even bother to try to CAS if it looks bad.
565 (not (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil new-owner
)))
566 #!+(and sb-thread sb-futex
)
567 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
568 (when (eql +lock-free
+ (sb!ext
:compare-and-swap
(mutex-state mutex
)
571 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil new-owner
)))
573 (bug "Old owner in free mutex: ~S" prev
))
577 (defun %%wait-for-mutex
(mutex new-owner to-sec to-usec stop-sec stop-usec
)
578 (declare (type mutex mutex
) (optimize (speed 3)))
579 (declare (sb!ext
:muffle-conditions sb
!ext
:compiler-note
))
581 (declare (ignore to-sec to-usec
))
587 (not (mutex-%owner mutex
)))
588 (not (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil
590 do
(return-from cas t
)
593 (sb!ext
:spin-loop-hint
))
594 ;; Check for pending interrupts.
595 (with-interrupts nil
)))
596 (declare (dynamic-extent #'cas
))
597 (sb!impl
::%%wait-for
#'cas stop-sec stop-usec
))
599 ;; This is a fairly direct translation of the Mutex 2 algorithm from
600 ;; "Futexes are Tricky" by Ulrich Drepper.
602 (when (eql +lock-free
+ old
)
603 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
)
606 (bug "Old owner in free mutex: ~S" prev
))
607 (return-from %%wait-for-mutex t
)))))
608 (prog ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
609 +lock-free
+ +lock-taken
+)))
610 ;; Got it right off the bat?
613 ;; Mark it as contested, and sleep. (Exception: it was just released.)
614 (when (or (eql +lock-contested
+ old
)
615 (not (eql +lock-free
+
616 (sb!ext
:compare-and-swap
617 (mutex-state mutex
) +lock-taken
+ +lock-contested
+))))
618 (when (eql 1 (with-pinned-objects (mutex)
619 (futex-wait (mutex-state-address mutex
)
620 (get-lisp-obj-address +lock-contested
+)
623 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
625 ;; 1 = ETIMEDOUT ***DONE***
626 ;; 2 = EINTR, a spurious wakeup
627 (return-from %%wait-for-mutex nil
)))
628 ;; Try to get it, still marking it as contested.
630 (sb!ext
:compare-and-swap
(mutex-state mutex
) +lock-free
+ +lock-contested
+))
631 ;; Update timeout if necessary.
633 (setf (values to-sec to-usec
)
634 (sb!impl
::relative-decoded-times stop-sec stop-usec
)))
639 (defun %wait-for-mutex
(mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep
)
640 (declare (sb!ext
:muffle-conditions sb
!ext
:compiler-note
))
641 (with-deadlocks (self mutex timeout
)
642 (with-interrupts (check-deadlock))
645 (return-from %wait-for-mutex
646 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec
)
649 ;; FIXME: substract elapsed time from timeout...
650 (setf (values to-sec to-usec stop-sec stop-usec deadlinep
)
651 (decode-timeout timeout
))
654 (define-deprecated-function :early
"1.0.37.33" get-mutex
(grab-mutex)
655 (mutex &optional new-owner
(waitp t
) (timeout nil
))
656 (declare (ignorable waitp timeout
))
657 (let ((new-owner (or new-owner
*current-thread
*)))
658 (or (%try-mutex mutex new-owner
)
661 (multiple-value-call #'%wait-for-mutex
662 mutex new-owner timeout
(decode-timeout timeout
))))))
664 (defun grab-mutex (mutex &key
(waitp t
) (timeout nil
))
665 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
666 the mutex is not immediately available, sleep until it is available.
668 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
669 GRAB-MUTEX should try to acquire the lock in the contested case.
671 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
672 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
673 that GRAB-MUTEX did -not- acquire the lock.
677 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
681 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
684 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
685 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
686 allows the call to be interrupted from sleep.
688 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
689 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
690 DEADLINE-TIMEOUT if the global deadline was due already on entering
693 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
696 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
699 (declare (ignorable waitp timeout
))
700 (let ((self *current-thread
*))
701 (or (%try-mutex mutex self
)
704 (multiple-value-call #'%wait-for-mutex
705 mutex self timeout
(decode-timeout timeout
))))))
707 (defun release-mutex (mutex &key
(if-not-owner :punt
))
708 "Release MUTEX by setting it to NIL. Wake up threads waiting for
711 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
714 If the current thread is not the owner of the mutex then it silently
715 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
716 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
717 IF-NOT-OWNER is :FORCE)."
718 (declare (type mutex mutex
))
719 ;; Order matters: set owner to NIL before releasing state.
720 (let* ((self *current-thread
*)
721 (old-owner (sb!ext
:compare-and-swap
(mutex-%owner mutex
) self nil
)))
722 (unless (eq self old-owner
)
724 ((:punt
) (return-from release-mutex nil
))
726 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner
))
728 (setf (mutex-%owner mutex
) nil
)
729 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
732 #!+(and sb-thread sb-futex
)
734 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
735 ;; unsigned-byte type this can be used:
737 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
738 ;; (unless (eql old +lock-free+)
739 ;; (setf (mutex-state mutex) +lock-free+)
740 ;; (with-pinned-objects (mutex)
741 ;; (futex-wake (mutex-state-address mutex) 1))))
742 (let ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
743 +lock-taken
+ +lock-free
+)))
744 (when (eql old
+lock-contested
+)
745 (sb!ext
:compare-and-swap
(mutex-state mutex
)
746 +lock-contested
+ +lock-free
+)
747 (with-pinned-objects (mutex)
748 (futex-wake (mutex-state-address mutex
) 1))))
752 ;;;; Waitqueues/condition variables
754 #!+(and sb-thread
(not sb-futex
))
756 (defun %waitqueue-enqueue
(thread queue
)
757 (setf (thread-waiting-for thread
) queue
)
758 (let ((head (waitqueue-%head queue
))
759 (tail (waitqueue-%tail queue
))
762 (setf (waitqueue-%head queue
) new
))
764 (setf (cdr tail
) new
))
765 (setf (waitqueue-%tail queue
) new
)
767 (defun %waitqueue-drop
(thread queue
)
768 (setf (thread-waiting-for thread
) nil
)
769 (let ((head (waitqueue-%head queue
)))
770 (do ((list head
(cdr list
))
773 (eq (car list
) thread
))
775 (let ((rest (cdr list
)))
777 (setf (cdr prev
) rest
))
779 (setf (waitqueue-%head queue
) rest
782 (setf (waitqueue-%tail queue
) prev
)))))))
784 (defun %waitqueue-wakeup
(queue n
)
786 (loop while
(plusp n
)
787 for next
= (let ((head (waitqueue-%head queue
))
788 (tail (waitqueue-%tail queue
)))
791 (setf (waitqueue-%head queue
) nil
792 (waitqueue-%tail queue
) nil
)
793 (setf (waitqueue-%head queue
) (cdr head
)))
796 do
(when (eq queue
(sb!ext
:compare-and-swap
797 (thread-waiting-for next
) queue nil
))
801 (defmethod print-object ((waitqueue waitqueue
) stream
)
802 (print-unreadable-object (waitqueue stream
:type t
:identity t
)
803 (format stream
"~@[~A~]" (waitqueue-name waitqueue
))))
805 (setf (fdocumentation 'waitqueue-name
'function
)
806 "The name of the waitqueue. Setfable."
807 (fdocumentation 'make-waitqueue
'function
)
808 "Create a waitqueue.")
810 #!+(and sb-thread sb-futex
)
811 (locally (declare (sb!ext
:muffle-conditions sb
!ext
:compiler-note
))
812 (define-structure-slot-addressor waitqueue-token-address
816 (declaim (inline %condition-wait
))
817 (defun %condition-wait
(queue mutex
818 timeout to-sec to-usec stop-sec stop-usec deadlinep
)
820 (declare (ignore queue mutex to-sec to-usec stop-sec stop-usec deadlinep
))
822 (sb!ext
:wait-for nil
:timeout timeout
) ; Yeah...
824 (let ((me *current-thread
*))
826 (assert (eq me
(mutex-%owner mutex
)))
827 (let ((status :interrupted
))
828 ;; Need to disable interrupts so that we don't miss grabbing
829 ;; the mutex on our way out.
835 (%with-cas-lock
((waitqueue-%owner queue
))
836 (%waitqueue-enqueue me queue
))
837 (release-mutex mutex
)
839 (or (flet ((wakeup ()
841 (unless (eq queue
(thread-waiting-for me
))
843 (declare (dynamic-extent #'wakeup
))
844 (allow-with-interrupts
845 (sb!impl
::%%wait-for
#'wakeup stop-sec stop-usec
)))
848 (with-pinned-objects (queue me
)
849 (setf (waitqueue-token queue
) me
)
850 (release-mutex mutex
)
851 ;; Now we go to sleep using futex-wait. If anyone else
852 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
853 ;; this comment, it will change the token, and so futex-wait
854 ;; returns immediately instead of sleeping. Ergo, no lost
855 ;; wakeup. We may get spurious wakeups, but that's ok.
857 (case (allow-with-interrupts
858 (futex-wait (waitqueue-token-address queue
)
859 (get-lisp-obj-address me
)
860 ;; our way of saying "no
868 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
870 ;; 2 = EINTR, a spurious wakeup
873 (%with-cas-lock
((waitqueue-%owner queue
))
874 (if (eq queue
(thread-waiting-for me
))
875 (%waitqueue-drop me queue
)
876 (unless (eq :ok status
)
877 ;; CONDITION-NOTIFY thinks we've been woken up, but really
878 ;; we're unwinding. Wake someone else up.
879 (%waitqueue-wakeup queue
1))))
880 ;; Update timeout for mutex re-aquisition unless we are
881 ;; already past the requested timeout.
882 (when (and (eq :ok status
) to-sec
)
883 (setf (values to-sec to-usec
)
884 (sb!impl
::relative-decoded-times stop-sec stop-usec
))
885 (when (and (zerop to-sec
) (not (plusp to-usec
)))
886 (setf status
:timeout
)))
887 ;; If we ran into deadline, try to get the mutex before
888 ;; signaling. If we don't unwind it will look like a normal
889 ;; return from user perspective.
890 (when (and (eq :timeout status
) deadlinep
)
891 (let ((got-it (%try-mutex mutex me
)))
892 (allow-with-interrupts
895 (return-from %condition-wait t
))
897 ;; The deadline may have changed.
898 (setf (values to-sec to-usec stop-sec stop-usec deadlinep
)
899 (decode-timeout timeout
))
900 (setf status
:ok
))))))
901 ;; Re-acquire the mutex for normal return.
902 (when (eq :ok status
)
903 (unless (or (%try-mutex mutex me
)
904 (allow-with-interrupts
905 (%wait-for-mutex mutex me timeout
907 stop-sec stop-usec deadlinep
)))
908 (setf status
:timeout
)))))
909 ;; Determine actual return value. :ok means (potentially
910 ;; spurious) wakeup => T. :timeout => NIL.
914 (multiple-value-bind (sec usec
)
915 (sb!impl
::relative-decoded-times stop-sec stop-usec
)
921 ;; The only case we return normally without re-acquiring
922 ;; the mutex is when there is a :TIMEOUT that runs out.
923 (bug "%CONDITION-WAIT: invalid status on normal return: ~S" status
))))))
924 (declaim (notinline %condition-wait
))
926 (defun condition-wait (queue mutex
&key timeout
)
927 "Atomically release MUTEX and start waiting on QUEUE until another thread
928 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on
929 QUEUE, at which point we re-acquire MUTEX and return T.
931 Spurious wakeups are possible.
933 If TIMEOUT is given, it is the maximum number of seconds to wait,
934 including both waiting for the wakeup and the time to re-acquire
935 MUTEX. When neither a wakeup nor a re-acquisition occurs within the
936 given time, returns NIL without re-acquiring MUTEX.
938 If CONDITION-WAIT unwinds, it may do so with or without MUTEX being
941 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY or
942 CONDITION-BROADCAST having occurred, the correct way to write code
943 that uses CONDITION-WAIT is to loop around the call, checking the
947 (defvar *queue* (make-waitqueue))
948 (defvar *lock* (make-mutex))
951 (defun pop-data (&optional timeout)
954 do (or (condition-wait *queue* *lock* :timeout timeout)
955 ;; Lock not held, must unwind without touching *data*.
956 (return-from pop-data nil)))
960 (defun push-data (data)
963 (condition-notify *queue*)))
966 (locally (declare (inline %condition-wait
))
967 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep
)
968 (decode-timeout timeout
)
970 (%condition-wait queue mutex timeout
971 to-sec to-usec stop-sec stop-usec deadlinep
)))))
973 (defun condition-notify (queue &optional
(n 1))
974 "Notify N threads waiting on QUEUE.
976 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
977 must be held by this thread during this call."
979 (declare (ignore queue n
))
981 (error "Not supported in unithread builds.")
983 (declare (type (and fixnum
(integer 1)) n
))
984 (/show0
"Entering CONDITION-NOTIFY")
988 (with-cas-lock ((waitqueue-%owner queue
))
989 (%waitqueue-wakeup queue n
))
992 ;; No problem if >1 thread notifies during the comment in condition-wait:
993 ;; as long as the value in queue-data isn't the waiting thread's id, it
994 ;; matters not what it is -- using the queue object itself is handy.
996 ;; XXX we should do something to ensure that the result of this setf
997 ;; is visible to all CPUs.
999 ;; ^-- surely futex_wake() involves a memory barrier?
1000 (setf (waitqueue-token queue
) queue
)
1001 (with-pinned-objects (queue)
1002 (futex-wake (waitqueue-token-address queue
) n
)))))
1004 (defun condition-broadcast (queue)
1005 "Notify all threads waiting on QUEUE.
1007 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
1008 must be held by this thread during this call."
1009 (condition-notify queue
1010 ;; On a 64-bit platform truncating M-P-F to an int
1011 ;; results in -1, which wakes up only one thread.
1013 most-positive-fixnum
)))
1018 (defstruct (semaphore (:copier nil
)
1019 (:constructor make-semaphore
1020 (&key name
((:count %count
) 0))))
1021 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
1022 should be considered an implementation detail, and may change in the
1024 (name nil
:type
(or null thread-name
) :read-only t
)
1025 (%count
0 :type
(integer 0))
1026 (waitcount 0 :type sb
!vm
:word
)
1027 (mutex (make-mutex :name
"semaphore lock") :read-only t
)
1028 (queue (make-waitqueue) :read-only t
))
1030 (setf (fdocumentation 'semaphore-name
'function
)
1031 "The name of the semaphore INSTANCE. Setfable."
1032 (fdocumentation 'make-semaphore
'function
)
1033 "Create a semaphore with the supplied COUNT and NAME.")
1035 (defstruct (semaphore-notification (:constructor make-semaphore-notification
())
1037 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
1038 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
1039 multiple threads are using the same notification object in parallel."
1040 (%status nil
:type boolean
))
1042 (setf (fdocumentation 'make-semaphore-notification
'function
)
1043 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
1046 (declaim (inline semaphore-notification-status
))
1047 (defun semaphore-notification-status (semaphore-notification)
1048 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
1049 SEMAPHORE-NOTIFICATION has succeeded since the notification object was created
1052 (semaphore-notification-%status semaphore-notification
))
1054 (declaim (inline clear-semaphore-notification
))
1055 (defun clear-semaphore-notification (semaphore-notification)
1056 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
1057 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
1059 (setf (semaphore-notification-%status semaphore-notification
) nil
)))
1061 (declaim (inline semaphore-count
))
1062 (defun semaphore-count (instance)
1063 "Returns the current count of the semaphore INSTANCE."
1065 (semaphore-%count instance
))
1067 (declaim (ftype (sfunction (semaphore (integer 1) (or boolean real
)
1068 (or null semaphore-notification
) symbol
)
1070 %decrement-semaphore
))
1071 (defun %decrement-semaphore
(semaphore n wait notification context
)
1072 (when (and notification
(semaphore-notification-status notification
))
1073 (with-simple-restart (continue "Clear notification status and continue.")
1074 (error "~@<Semaphore notification object status not cleared on ~
1075 entry to ~S on ~S.~:@>"
1077 (clear-semaphore-notification notification
))
1079 ;; A more direct implementation based directly on futexes should be
1082 ;; We need to disable interrupts so that we don't forget to
1083 ;; decrement the waitcount (which would happen if an asynch
1084 ;; interrupt should catch us on our way out from the loop.)
1086 ;; FIXME: No timeout on initial mutex acquisition.
1087 (with-system-mutex ((semaphore-mutex semaphore
) :allow-with-interrupts t
)
1088 (flet ((success (new-count)
1090 (setf (semaphore-%count semaphore
) new-count
)
1092 (setf (semaphore-notification-%status notification
) t
)))))
1093 ;; Quick check: can we decrement right away? If not, return or
1094 ;; enter the wait loop.
1096 ((let ((old-count (semaphore-%count semaphore
)))
1097 (when (>= old-count n
)
1098 (success (- old-count n
)))))
1103 (binding* ((old-count nil
)
1104 (timeout (when (realp wait
) wait
))
1105 ((to-sec to-usec stop-sec stop-usec deadlinep
)
1107 (decode-timeout timeout
))))
1108 ;; Need to use ATOMIC-INCF despite the lock, because
1109 ;; on our way out from here we might not be locked
1110 ;; anymore -- so another thread might be tweaking this
1111 ;; in parallel using ATOMIC-DECF. No danger over
1112 ;; overflow, since there it at most one increment per
1113 ;; thread waiting on the semaphore.
1114 (sb!ext
:atomic-incf
(semaphore-waitcount semaphore
))
1115 (loop until
(>= (setf old-count
(semaphore-%count semaphore
)) n
)
1116 do
(multiple-value-bind (wakeup-p remaining-sec remaining-usec
)
1118 (semaphore-queue semaphore
)
1119 (semaphore-mutex semaphore
)
1120 timeout to-sec to-usec stop-sec stop-usec deadlinep
)
1121 (when (or (not wakeup-p
)
1122 (and (eql remaining-sec
0)
1123 (eql remaining-usec
0)))
1124 (return-from %decrement-semaphore nil
)) ; timeout
1126 (setf to-sec remaining-sec
1127 to-usec remaining-usec
))))
1128 (success (- old-count n
)))
1129 ;; Need to use ATOMIC-DECF as we may unwind without the
1131 (sb!ext
:atomic-decf
(semaphore-waitcount semaphore
))))))))
1133 (declaim (ftype (sfunction (semaphore &key
1135 (:timeout
(real (0)))
1136 (:notification semaphore-notification
))
1137 (or null
(integer 0)))
1139 (defun wait-on-semaphore (semaphore &key
(n 1) timeout notification
)
1140 "Decrement the count of SEMAPHORE by N if the count would not be negative.
1142 Else blocks until the semaphore can be decremented. Returns the new count of
1143 SEMAPHORE on success.
1145 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
1146 cannot be decremented in that time, returns NIL without decrementing the
1149 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
1150 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
1151 decrements the count, the status is set to T."
1152 (%decrement-semaphore
1153 semaphore n
(or timeout t
) notification
'wait-on-semaphore
))
1155 (declaim (ftype (sfunction (semaphore &optional
1156 (integer 1) semaphore-notification
)
1157 (or null
(integer 0)))
1159 (defun try-semaphore (semaphore &optional
(n 1) notification
)
1160 "Try to decrement the count of SEMAPHORE by N. If the count were to
1161 become negative, punt and return NIL, otherwise return the new count of
1164 If NOTIFICATION is given it must be a semaphore notification object
1165 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1166 the status is set to T."
1167 (%decrement-semaphore semaphore n nil notification
'try-semaphore
))
1169 (defun signal-semaphore (semaphore &optional
(n 1))
1170 "Increment the count of SEMAPHORE by N. If there are threads waiting
1171 on this semaphore, then N of them is woken up."
1172 (declare (type (integer 1) n
))
1173 ;; Need to disable interrupts so that we don't lose a wakeup after
1174 ;; we have incremented the count.
1175 (with-system-mutex ((semaphore-mutex semaphore
) :allow-with-interrupts t
)
1176 (let ((waitcount (semaphore-waitcount semaphore
))
1177 (count (incf (semaphore-%count semaphore
) n
)))
1178 (when (plusp waitcount
)
1179 (condition-notify (semaphore-queue semaphore
) (min waitcount count
))))))
1182 ;;;; Job control, independent listeners
1184 (defstruct (session (:copier nil
))
1185 (lock (make-mutex :name
"session lock"))
1187 (interactive-threads nil
)
1188 (interactive-threads-queue (make-waitqueue)))
1190 (defvar *session
* nil
)
1192 ;;; The debugger itself tries to acquire the session lock, don't let
1193 ;;; funny situations (like getting a sigint while holding the session
1194 ;;; lock) occur. At the same time we need to allow interrupts while
1195 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1196 ;;; be interruptible.
1198 ;;; Take care: we sometimes need to obtain the session lock while
1199 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1200 ;;; _after_ getting a session lock! (Deadlock risk.)
1202 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1204 (defmacro with-session-lock
((session) &body body
)
1205 `(with-system-mutex ((session-lock ,session
) :allow-with-interrupts t
)
1208 (defun new-session ()
1209 (make-session :threads
(list *current-thread
*)
1210 :interactive-threads
(list *current-thread
*)))
1212 (defun init-job-control ()
1213 (/show0
"Entering INIT-JOB-CONTROL")
1214 (setf *session
* (new-session))
1215 (/show0
"Exiting INIT-JOB-CONTROL"))
1217 (defun %delete-thread-from-session
(thread session
)
1218 (with-session-lock (session)
1219 (let ((was-foreground (eq thread
(foreground-thread session
))))
1220 (setf (session-threads session
)
1221 ;; DELQ never conses, but DELETE does. (FIXME)
1222 (delq thread
(session-threads session
))
1223 (session-interactive-threads session
)
1224 (delq thread
(session-interactive-threads session
)))
1225 (when was-foreground
1226 (condition-broadcast (session-interactive-threads-queue session
))))))
1228 (defun call-with-new-session (fn)
1229 (%delete-thread-from-session
*current-thread
* *session
*)
1230 (let ((*session
* (new-session)))
1233 (defmacro with-new-session
(args &body forms
)
1234 (declare (ignore args
)) ;for extensibility
1235 (with-unique-names (fb-name)
1236 `(labels ((,fb-name
() ,@forms
))
1237 (call-with-new-session (function ,fb-name
)))))
1239 ;;; Remove thread from its session, if it has one.
1241 (defun handle-thread-exit (thread)
1242 (/show0
"HANDLING THREAD EXIT")
1243 (when *exit-in-process
*
1245 ;; Lisp-side cleanup
1246 (with-all-threads-lock
1247 (setf (thread-%alive-p thread
) nil
)
1248 (setf (thread-os-thread thread
)
1249 (ldb (byte sb
!vm
:n-word-bits
0) -
1))
1250 (setq *all-threads
* (delq thread
*all-threads
*))
1252 (%delete-thread-from-session thread
*session
*))))
1254 (defvar sb
!ext
:*invoke-debugger-hook
* nil
1255 "This is either NIL or a designator for a function of two arguments,
1256 to be run when the debugger is about to be entered. The function is
1257 run with *INVOKE-DEBUGGER-HOOK* bound to NIL to minimize recursive
1258 errors, and receives as arguments the condition that triggered
1259 debugger entry and the previous value of *INVOKE-DEBUGGER-HOOK*
1261 This mechanism is an SBCL extension similar to the standard *DEBUGGER-HOOK*.
1262 In contrast to *DEBUGGER-HOOK*, it is observed by INVOKE-DEBUGGER even when
1265 (defun %exit-other-threads
()
1266 ;; Grabbing this lock prevents new threads from
1267 ;; being spawned, and guarantees that *ALL-THREADS*
1269 (with-deadline (:seconds nil
:override t
)
1270 (grab-mutex *make-thread-lock
*)
1271 (let ((timeout sb
!ext
:*exit-timeout
*)
1272 (code *exit-in-process
*)
1273 (current *current-thread
*)
1276 ;; Don't invoke the debugger on errors in cleanup forms in unwind-protect
1277 (setf sb
!ext
:*invoke-debugger-hook
*
1279 (sb!debug
::debugger-disabled-hook c h
:quit nil
)
1280 (abort-thread :allow-exit t
)))
1281 (dolist (thread (list-all-threads))
1282 (cond ((eq thread current
))
1283 ((main-thread-p thread
)
1288 (terminate-thread thread
)
1289 (push thread joinees
))
1290 (interrupt-thread-error ())))))
1291 (with-progressive-timeout (time-left :seconds timeout
)
1292 (dolist (thread joinees
)
1293 (join-thread thread
:default t
:timeout
(time-left)))
1294 ;; Need to defer till others have joined, because when main
1295 ;; thread exits, we're gone. Can't use TERMINATE-THREAD -- would
1296 ;; get the exit code wrong.
1302 (setf *exit-in-process
* (list code
))
1303 (throw 'sb
!impl
::%end-of-the-world t
)))
1304 (interrupt-thread-error ()))
1305 ;; Normally this never finishes, as once the main-thread unwinds we
1306 ;; exit with the right code, but if times out before that happens,
1307 ;; we will exit after returning -- or rathe racing the main thread
1308 ;; to calling OS-EXIT.
1309 (join-thread main
:default t
:timeout
(time-left)))))))
1311 (defun terminate-session ()
1312 "Kill all threads in session except for this one. Does nothing if current
1313 thread is not the foreground thread."
1314 ;; FIXME: threads created in other threads may escape termination
1315 (let* ((session *session
*)
1316 (to-kill (with-session-lock (session)
1317 (and (eq *current-thread
* (foreground-thread session
))
1318 (session-threads session
)))))
1319 ;; do the kill after dropping the mutex; unwind forms in dying
1320 ;; threads may want to do session things
1321 (dolist (thread to-kill
)
1322 (unless (eq thread
*current-thread
*)
1323 ;; terminate the thread but don't be surprised if it has
1324 ;; exited in the meantime
1325 (handler-case (terminate-thread thread
)
1326 (interrupt-thread-error ()))))))
1328 ;;; called from top of invoke-debugger
1329 (defun debugger-wait-until-foreground-thread (stream)
1330 "Returns T if thread had been running in background, NIL if it was
1332 (declare (ignore stream
))
1336 (with-session-lock (*session
*)
1337 (not (member *current-thread
*
1338 (session-interactive-threads *session
*))))
1341 (defun get-foreground ()
1344 (let ((session *session
*)
1347 (/show0
"Looping in GET-FOREGROUND")
1348 (with-session-lock (session)
1350 ((interactive-threads (session-interactive-threads session
)))
1352 ((null interactive-threads
)
1353 (setf was-foreground nil
1354 interactive-threads
(list *current-thread
*)))
1355 ((not (eq (first interactive-threads
) *current-thread
*))
1356 (setf was-foreground nil
)
1357 (unless (member *current-thread
* interactive-threads
)
1358 (setf interactive-threads
1359 (append interactive-threads
(list *current-thread
*))))
1361 (session-interactive-threads-queue session
)
1362 (session-lock session
)))
1364 (unless was-foreground
1365 (format *query-io
* "Resuming thread ~A~%" *current-thread
*))
1366 (return-from get-foreground t
))))))))
1368 (defun release-foreground (&optional next
)
1369 "Background this thread. If NEXT is supplied, arrange for it to
1370 have the foreground next."
1371 #!-sb-thread
(declare (ignore next
))
1374 (let ((session *session
*))
1375 (with-session-lock (session)
1377 ((interactive-threads (session-interactive-threads session
)))
1378 (setf interactive-threads
1379 (delete *current-thread
* interactive-threads
))
1380 (when (and next
(thread-alive-p next
))
1381 (setf interactive-threads
1382 (list* next
(delete next interactive-threads
))))
1383 (condition-broadcast (session-interactive-threads-queue session
))))))
1385 (defun interactive-threads (&optional
(session *session
*))
1386 "Return the interactive threads of SESSION defaulting to the current
1388 (session-interactive-threads session
))
1390 (defun foreground-thread (&optional
(session *session
*))
1391 "Return the foreground thread of SESSION defaulting to the current
1393 (first (interactive-threads session
)))
1395 (defun make-listener-thread (tty-name)
1396 (assert (probe-file tty-name
))
1397 (let* ((in (sb!unix
:unix-open
(namestring tty-name
) sb
!unix
:o_rdwr
#o666
))
1398 (out (sb!unix
:unix-dup in
))
1399 (err (sb!unix
:unix-dup in
)))
1400 (labels ((thread-repl ()
1401 (sb!unix
::unix-setsid
)
1402 (let* ((sb!impl
::*stdin
*
1403 (make-fd-stream in
:input t
:buffering
:line
1406 (make-fd-stream out
:output t
:buffering
:line
1409 (make-fd-stream err
:output t
:buffering
:line
1412 (make-fd-stream err
:input t
:output t
1415 (sb!impl
::*descriptor-handlers
* nil
))
1416 (with-new-session ()
1418 (sb!impl
::toplevel-repl nil
)
1419 (flush-standard-output-streams))))))
1420 (make-thread #'thread-repl
))))
1426 (defun initial-thread-function-trampoline (thread setup-sem real-function arguments
)
1427 ;; Can't initiate GC before *current-thread* is set, otherwise the
1428 ;; locks grabbed by SUB-GC wouldn't function.
1429 ;; Other threads can GC with impunity.
1430 (setf *current-thread
* thread
; is thread-local already
1431 (thread-os-thread thread
) (current-thread-os-thread)
1432 (thread-primitive-thread thread
) (sap-int (current-thread-sap)))
1433 ;; *ALLOC-SIGNAL* is made thread-local by create_thread_struct()
1434 ;; so this assigns into TLS, not the global value.
1435 (setf sb
!vm
:*alloc-signal
* *default-alloc-signal
*)
1436 (with-mutex ((thread-result-lock thread
))
1437 (let* ((thread-list (list thread thread
))
1438 (session-cons (cdr thread-list
)))
1439 (with-all-threads-lock
1440 (setf (cdr thread-list
) *all-threads
*
1441 *all-threads
* thread-list
))
1442 (let ((session *session
*))
1443 (with-session-lock (session)
1444 (setf (cdr session-cons
) (session-threads session
)
1445 (session-threads session
) session-cons
))))
1446 (setf (thread-%alive-p thread
) t
)
1449 (signal-semaphore setup-sem
)
1450 ;; setup-sem was dx-allocated, set it to NIL so that the
1451 ;; backtrace doesn't get confused
1452 (setf setup-sem nil
))
1454 ;; Using handling-end-of-the-world would be a bit tricky
1455 ;; due to other catches and interrupts, so we essentially
1456 ;; re-implement it here. Once and only once more.
1457 (catch 'sb
!impl
::toplevel-catcher
1458 (catch 'sb
!impl
::%end-of-the-world
1459 (catch '%abort-thread
1460 (restart-bind ((abort
1462 (throw '%abort-thread nil
))
1465 (format stream
"~@<abort thread (~a)~@:>"
1466 *current-thread
*))))
1469 (with-local-interrupts
1470 (sb!unix
::unblock-deferrable-signals
)
1471 (setf (thread-result thread
)
1473 (multiple-value-list
1475 (catch '%return-from-thread
1476 (apply real-function arguments
))
1477 (when *exit-in-process
*
1478 (sb!impl
::call-exit-hooks
))))
1480 (sb!kernel
::gc-safepoint
))))
1481 ;; we're going down, can't handle interrupts
1482 ;; sanely anymore. gc remains enabled.
1483 (block-deferrable-signals)
1484 ;; we don't want to run interrupts in a dead
1485 ;; thread when we leave without-interrupts.
1486 ;; this potentially causes important
1487 ;; interupts to be lost: sigint comes to
1489 (setq *interrupt-pending
* nil
)
1491 (setq *thruption-pending
* nil
)
1492 (handle-thread-exit thread
))))))))
1495 (defun make-thread (function &key name arguments ephemeral
)
1496 "Create a new thread of NAME that runs FUNCTION with the argument
1497 list designator provided (defaults to no argument). Thread exits when
1498 the function returns. The return values of FUNCTION are kept around
1499 and can be retrieved by JOIN-THREAD.
1501 Invoking the initial ABORT restart established by MAKE-THREAD
1502 terminates the thread.
1504 See also: RETURN-FROM-THREAD, ABORT-THREAD."
1505 #!-sb-thread
(declare (ignore function name arguments ephemeral
))
1506 #!-sb-thread
(error "Not supported in unithread builds.")
1507 #!+sb-thread
(assert (or (atom arguments
)
1508 (null (cdr (last arguments
))))
1510 "Argument passed to ~S, ~S, is an improper list."
1511 'make-thread arguments
)
1513 (let ((thread (%make-thread
:name name
:%ephemeral-p ephemeral
)))
1514 (declare (inline make-semaphore
1517 (let* ((setup-sem (make-semaphore :name
"Thread setup semaphore"))
1518 (real-function (coerce function
'function
))
1519 (arguments (ensure-list arguments
))
1520 #!+(or win32 darwin
)
1521 (fp-modes (dpb 0 sb
!vm
:float-sticky-bits
;; clear accrued bits
1522 (sb!vm
:floating-point-modes
))))
1523 (declare (dynamic-extent setup-sem
))
1524 (dx-flet ((initial-thread-function ()
1525 ;; Inherit parent thread's FP modes
1526 #!+(or win32 darwin
)
1527 (setf (sb!vm
:floating-point-modes
) fp-modes
)
1528 ;; As it is, this lambda must not cons until we are
1529 ;; ready to run GC. Be careful.
1530 (initial-thread-function-trampoline thread setup-sem
1531 real-function arguments
)))
1532 ;; Holding mutexes or waiting on sempahores inside WITHOUT-GCING will lock up
1533 (aver (not *gc-inhibit
*))
1534 ;; Keep INITIAL-FUNCTION in the dynamic extent until the child
1535 ;; thread is initialized properly. Wrap the whole thing in
1536 ;; WITHOUT-INTERRUPTS (via WITH-SYSTEM-MUTEX) because we pass
1537 ;; INITIAL-FUNCTION to another thread.
1538 ;; (Does WITHOUT-INTERRUPTS really matter now that it's DXed?)
1539 (with-system-mutex (*make-thread-lock
*)
1541 (%create-thread
(get-lisp-obj-address #'initial-thread-function
)))
1543 (wait-on-semaphore setup-sem
)))))
1544 (or thread
(error "Could not create a new thread."))))
1546 (defun join-thread (thread &key
(default nil defaultp
) timeout
)
1547 "Suspend current thread until THREAD exits. Return the result values
1548 of the thread function.
1550 If THREAD does not exit within TIMEOUT seconds and DEFAULT is
1551 supplied, return two values: 1) DEFAULT 2) :TIMEOUT. If DEFAULT is not
1552 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-PROBLEM equal
1555 If THREAD does not exit normally (i.e. aborted) and DEFAULT is
1556 supplied, return two values: 1) DEFAULT 2) :ABORT. If DEFAULT is not
1557 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-PROBLEM equal
1560 If THREAD is the current thread, signal a JOIN-THREAD-ERROR with
1561 JOIN-THREAD-PROBLEM equal to :SELF-JOIN.
1563 Trying to join the main thread causes JOIN-THREAD to block until
1564 TIMEOUT occurs or the process exits: when the main thread exits, the
1565 entire process exits.
1567 NOTE: Return convention in case of a timeout is experimental and
1569 (when (eq thread
*current-thread
*)
1570 (error 'join-thread-error
:thread thread
:problem
:self-join
))
1572 (let ((lock (thread-result-lock thread
))
1579 (allow-with-interrupts
1580 ;; Don't use the timeout if the thread is
1581 ;; not alive anymore.
1582 (grab-mutex lock
:timeout
(and (thread-alive-p thread
)
1584 ((listp (thread-result thread
))
1585 (return-from join-thread
1586 (values-list (thread-result thread
))))
1588 (setf problem
:abort
)))
1590 (release-mutex lock
))))
1592 (values default problem
)
1593 (error 'join-thread-error
:thread thread
:problem problem
))))
1595 (defun destroy-thread (thread)
1596 (terminate-thread thread
))
1599 (declaim (sb!ext
:deprecated
1600 :late
("SBCL" "1.2.15")
1601 (function destroy-thread
:replacement terminate-thread
)))
1604 (defun enter-foreign-callback (index return arguments
)
1605 (let ((thread (without-gcing
1606 ;; Hold off GCing until *current-thread* is set up
1607 (setf *current-thread
*
1608 (make-foreign-thread :name
"foreign callback")))))
1610 (sb!alien
::enter-alien-callback index return arguments
)))
1611 (initial-thread-function-trampoline thread nil
#'enter nil
))))
1613 (defmacro with-interruptions-lock
((thread) &body body
)
1614 `(with-system-mutex ((thread-interruptions-lock ,thread
))
1617 ;;; Called from the signal handler.
1618 #!-
(or sb-thruption win32
)
1619 (defun run-interruption ()
1620 (let ((interruption (with-interruptions-lock (*current-thread
*)
1621 (pop (thread-interruptions *current-thread
*)))))
1622 ;; If there is more to do, then resignal and let the normal
1623 ;; interrupt deferral mechanism take care of the rest. From the
1624 ;; OS's point of view the signal we are in the handler for is no
1625 ;; longer pending, so the signal will not be lost.
1626 (when (thread-interruptions *current-thread
*)
1627 (kill-safely (thread-os-thread *current-thread
*) sb
!unix
:sigpipe
))
1629 (funcall interruption
))))
1632 (defun run-interruption (*current-internal-error-context
*)
1633 (in-interruption () ;the non-thruption code does this in the signal handler
1634 (let ((interruption (with-interruptions-lock (*current-thread
*)
1635 (pop (thread-interruptions *current-thread
*)))))
1637 (funcall interruption
)
1638 ;; I tried implementing this function as an explicit LOOP, because
1639 ;; if we are currently processing the thruption queue, why not do
1640 ;; all of them in one go instead of one-by-one?
1642 ;; I still think LOOPing would be basically the right thing
1643 ;; here. But suppose some interruption unblocked deferrables.
1644 ;; Will the next one be happy with that? The answer is "no", at
1645 ;; least in the sense that there are tests which check that
1646 ;; deferrables are blocked at the beginning of a thruption, and
1647 ;; races that make those tests fail. Whether the tests are
1648 ;; misguided or not, it seems easier/cleaner to loop implicitly
1649 ;; -- and it's also what AK had implemented in the first place.
1651 ;; The implicit loop is achieved by returning to C, but having C
1652 ;; call back to us immediately. The runtime will reset the sigmask
1653 ;; in the mean time.
1655 (setf *thruption-pending
* t
)))))
1657 (defun interrupt-thread (thread function
)
1658 "Interrupt THREAD and make it run FUNCTION.
1660 The interrupt is asynchronous, and can occur anywhere with the exception of
1661 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1663 FUNCTION is called with interrupts disabled, under
1664 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1665 enable interrupts internally, in most cases FUNCTION should either enter
1666 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1667 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1669 When a thread receives multiple interrupts, they are executed in the order
1670 they were sent -- first in, first out.
1672 This means that a great degree of care is required to use INTERRUPT-THREAD
1673 safely and sanely in a production environment. The general recommendation is
1674 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1675 entirely from production environments -- it is simply exceedingly hard to use
1678 With those caveats in mind, what you need to know when using it:
1680 * If calling FUNCTION causes a non-local transfer of control (ie. an
1681 unwind), all normal cleanup forms will be executed.
1683 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1684 it is just as if that had happened due to a regular GO, THROW, or
1685 RETURN-FROM: the interrupted cleanup form and those following it in the
1686 same UNWIND-PROTECT do not get executed.
1688 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1689 frankly an unreasonable expectation for third party libraries, especially
1690 given that asynch-unwind-safety does not compose: a function calling
1691 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1693 This means that in order for an asynch unwind to be safe, the entire
1694 callstack at the point of interruption needs to be asynch-unwind-safe.
1696 * In addition to asynch-unwind-safety you must consider the issue of
1697 reentrancy. INTERRUPT-THREAD can cause function that are never normally
1698 called recursively to be re-entered during their dynamic contour,
1699 which may cause them to misbehave. (Consider binding of special variables,
1700 values of global variables, etc.)
1702 Taken together, these two restrict the \"safe\" things to do using
1703 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1704 interactive development use is using it to force entry to debugger to inspect
1705 the state of a thread:
1707 (interrupt-thread thread #'break)
1709 Short version: be careful out there."
1710 #!+(and (not sb-thread
) win32
)
1711 #!+(and (not sb-thread
) win32
)
1712 (declare (ignore thread
))
1713 (with-interrupt-bindings
1714 (with-interrupts (funcall function
)))
1715 #!-
(and (not sb-thread
) win32
)
1716 (let ((os-thread (thread-os-thread thread
)))
1717 (cond ((= os-thread
(ldb (byte sb
!vm
:n-word-bits
0) -
1))
1718 (error 'interrupt-thread-error
:thread thread
))
1721 (with-interruptions-lock (thread)
1722 ;; Append to the end of the interruptions queue. It's
1723 ;; O(N), but it does not hurt to slow interruptors down a
1724 ;; bit when the queue gets long.
1725 (setf (thread-interruptions thread
)
1726 (append (thread-interruptions thread
)
1731 (allow-with-interrupts
1732 (funcall function
))))))))
1733 (when (and (minusp (wake-thread os-thread
))
1734 ;; The interrupt queue has been processed by
1735 ;; some other interrupt.
1736 (progn (barrier (:memory
))
1738 (error 'interrupt-thread-error
:thread thread
)))))))
1740 (defun terminate-thread (thread)
1741 "Terminate the thread identified by THREAD, by interrupting it and
1742 causing it to call SB-EXT:ABORT-THREAD with :ALLOW-EXIT T.
1744 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that
1745 eg. thread executing
1750 (setf foo (get-foo))
1753 ;; An interrupt occurring inside the cleanup clause
1754 ;; will cause cleanups from the current UNWIND-PROTECT
1756 (release-foo foo))))
1758 might miss calling RELEASE-FOO despite GET-FOO having returned true if
1759 the interrupt occurs inside the cleanup clause, eg. during execution
1762 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need
1763 to use WITHOUT-INTERRUPTS:
1766 (sb-sys:without-interrupts
1769 (setf foo (sb-sys:allow-with-interrupts
1771 (sb-sys:with-local-interrupts
1774 (release-foo foo)))))
1776 Since most libraries using UNWIND-PROTECT do not do this, you should never
1777 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1778 (interrupt-thread thread
(lambda () (abort-thread :allow-exit t
))))
1780 (define-alien-routine "thread_yield" int
)
1782 (setf (fdocumentation 'thread-yield
'function
)
1783 "Yield the processor to other threads.")
1785 ;;; internal use only. If you think you need to use these, either you
1786 ;;; are an SBCL developer, are doing something that you should discuss
1787 ;;; with an SBCL developer first, or are doing something that you
1788 ;;; should probably discuss with a professional psychiatrist first
1792 (sb!ext
:defglobal sb
!vm
::*free-tls-index
* 0)
1793 ;; Keep in sync with 'compiler/generic/parms.lisp'
1794 #!+ppc
; only PPC uses a separate symbol for the TLS index lock
1795 (!defglobal sb
!vm
::*tls-index-lock
* 0)
1797 (defun %symbol-value-in-thread
(symbol thread
)
1798 ;; Prevent the thread from dying completely while we look for the TLS
1800 (with-all-threads-lock
1801 (if (thread-alive-p thread
)
1802 (let* ((offset (get-lisp-obj-address (symbol-tls-index symbol
)))
1803 (obj (sap-ref-lispobj (int-sap (thread-primitive-thread thread
)) offset
))
1804 (tl-val (get-lisp-obj-address obj
)))
1805 (cond ((zerop offset
)
1806 (values nil
:no-tls-value
))
1807 ((or (eql tl-val sb
!vm
:no-tls-value-marker-widetag
)
1808 (eql tl-val sb
!vm
:unbound-marker-widetag
))
1809 (values nil
:unbound-in-thread
))
1812 (values nil
:thread-dead
))))
1814 (defun %set-symbol-value-in-thread
(symbol thread value
)
1815 ;; Prevent the thread from dying completely while we look for the TLS
1817 (with-all-threads-lock
1818 (if (thread-alive-p thread
)
1819 (let ((offset (get-lisp-obj-address (symbol-tls-index symbol
))))
1820 (cond ((zerop offset
)
1821 (values nil
:no-tls-value
))
1823 (setf (sap-ref-lispobj (int-sap (thread-primitive-thread thread
))
1826 (values value
:ok
))))
1827 (values nil
:thread-dead
))))
1829 (define-alien-variable tls-index-start unsigned-int
)
1831 ;; Get values from the TLS area of the current thread.
1832 (defun %thread-local-references
()
1833 ;; TLS-INDEX-START is a word number relative to thread base.
1834 ;; *FREE-TLS-INDEX* - which is only manipulated by machine code - is an
1835 ;; offset from thread base to the next usable TLS cell as a raw word
1836 ;; manifesting in Lisp as a fixnum. Convert it from byte number to word
1837 ;; number before using it as the upper bound for the sequential scan.
1838 (loop for index from tls-index-start
1839 ;; On x86-64, mask off the sign bit. It is used as a semaphore.
1840 below
(ash (logand #!+x86-64 most-positive-fixnum
1841 sb
!vm
::*free-tls-index
*)
1842 (+ (- sb
!vm
:word-shift
) sb
!vm
:n-fixnum-tag-bits
))
1843 for obj
= (sb!kernel
:%make-lisp-obj
1844 (sb!sys
:sap-int
(sb!vm
::current-thread-offset-sap index
)))
1845 unless
(or (member (widetag-of obj
)
1846 `(,sb
!vm
:no-tls-value-marker-widetag
1847 ,sb
!vm
:unbound-marker-widetag
))
1848 (typep obj
'(or fixnum character
))
1850 collect obj into seen
1851 finally
(return seen
))))
1853 (defun symbol-value-in-thread (symbol thread
&optional
(errorp t
))
1854 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1857 If the value cannot be retrieved (because the thread has exited or because it
1858 has no local binding for NAME) and ERRORP is true signals an error of type
1859 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1860 NIL, and a secondary value of NIL.
1862 Can also be used with SETF to change the thread-local value of SYMBOL.
1864 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1865 mechanism for inter-thread communication."
1866 (declare (symbol symbol
) (thread thread
))
1868 (multiple-value-bind (res status
) (%symbol-value-in-thread symbol thread
)
1872 (error 'symbol-value-in-thread-error
1875 :info
(list :read status
))
1879 (values (symbol-value symbol
) t
)
1881 (error 'symbol-value-in-thread-error
1884 :info
(list :read
:unbound-in-thread
))
1887 (defun (setf symbol-value-in-thread
) (value symbol thread
&optional
(errorp t
))
1888 (declare (symbol symbol
) (thread thread
))
1890 (multiple-value-bind (res status
) (%set-symbol-value-in-thread symbol thread value
)
1894 (error 'symbol-value-in-thread-error
1897 :info
(list :write status
))
1901 (values (setf (symbol-value symbol
) value
) t
)
1903 (error 'symbol-value-in-thread-error
1906 :info
(list :write
:unbound-in-thread
))
1913 (defun thread-stepping ()
1914 (sap-ref-lispobj (current-thread-sap)
1915 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
)))
1917 (defun (setf thread-stepping
) (value)
1918 (setf (sap-ref-lispobj (current-thread-sap)
1919 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
))