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))))))
136 "Signalled when joining a thread fails due to abnormal exit of the thread
137 to be joined. The offending thread can be accessed using
138 THREAD-ERROR-THREAD."))
140 (define-deprecated-function :late "1.0.29.17" join-thread-error-thread thread-error-thread
142 (thread-error-thread condition))
144 (define-condition interrupt-thread-error (thread-error) ()
145 (:report (lambda (c s)
146 (format s "Interrupt thread failed: thread ~A has exited."
147 (thread-error-thread c))))
150 "Signalled when interrupting a thread fails because the thread has already
151 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
153 (define-deprecated-function :late "1.0.29.17" interrupt-thread-error-thread thread-error-thread
155 (thread-error-thread condition))
157 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
158 ;;; necessary because threads are only supported with the conservative
159 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
160 ;;; are treated as references.
162 ;;; set the doc here because in early-thread FDOCUMENTATION is not
165 (setf (fdocumentation '*current-thread* 'variable)
166 "Bound in each thread to the thread itself.")
170 (fdocumentation 'thread-name 'function)
171 "Name of the thread. Can be assigned to using SETF. Thread names can be
172 arbitrary printable objects, and need not be unique.")
174 (def!method print-object ((thread thread) stream)
175 (print-unreadable-object (thread stream :type t :identity t)
176 (let* ((cookie (list thread))
177 (info (if (thread-alive-p thread)
180 (join-thread thread :default cookie))))
181 (state (if (eq :running info)
184 (thread-waiting-for thread))))
187 (list "waiting on:" (cdr thing)
188 "timeout: " (car thing)))
192 (list "waiting on:" thing))))
193 (if (eq cookie (car info))
196 (values (when (eq :finished state)
200 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
206 (defun print-lock (lock name owner stream)
207 (let ((*print-circle* t))
208 (print-unreadable-object (lock stream :type t :identity (not name))
210 (format stream "~@[~S ~]~2I~_owner: ~S" name owner)
211 (format stream "~@[~S ~](free)" name)))))
213 (def!method print-object ((mutex mutex) stream)
214 (print-lock mutex (mutex-name mutex) (mutex-owner mutex) stream))
216 (defun thread-alive-p (thread)
218 "Return T if THREAD is still alive. Note that the return value is
219 potentially stale even before the function returns, as the thread may exit at
221 (thread-%alive-p thread))
223 (defun thread-emphemeral-p (thread)
225 "Return T if THREAD is `ephemeral', which indicates that this thread is
226 used by SBCL for internal purposes, and specifically that it knows how to
227 to terminate this thread cleanly prior to core file saving without signalling
228 an error in that case."
229 (thread-%ephemeral-p thread))
231 ;; A thread is eligible for gc iff it has finished and there are no
232 ;; more references to it. This list is supposed to keep a reference to
233 ;; all running threads.
234 (defvar *all-threads* ())
235 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
237 (defvar *default-alloc-signal* nil)
239 (defmacro with-all-threads-lock (&body body)
240 `(with-system-mutex (*all-threads-lock*)
243 (defun list-all-threads ()
245 "Return a list of the live threads. Note that the return value is
246 potentially stale even before the function returns, as new threads may be
247 created and old ones may exit at any time."
248 (with-all-threads-lock
249 (copy-list *all-threads*)))
251 (declaim (inline current-thread-sap))
252 (defun current-thread-sap ()
253 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
255 (declaim (inline current-thread-os-thread))
256 (defun current-thread-os-thread ()
258 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
262 (defvar *initial-thread* nil)
263 (defvar *make-thread-lock*)
265 (defun init-initial-thread ()
266 (/show0 "Entering INIT-INITIAL-THREAD")
267 (setf sb!impl::*exit-lock* (make-mutex :name "Exit Lock")
268 *make-thread-lock* (make-mutex :name "Make-Thread Lock"))
269 (let ((initial-thread (%make-thread :name "main thread"
271 :os-thread (current-thread-os-thread))))
272 (setq *initial-thread* initial-thread
273 *current-thread* initial-thread)
274 (grab-mutex (thread-result-lock *initial-thread*))
275 ;; Either *all-threads* is empty or it contains exactly one thread
276 ;; in case we are in reinit since saving core with multiple
277 ;; threads doesn't work.
278 (setq *all-threads* (list initial-thread))))
280 (defun main-thread ()
281 "Returns the main thread of the process."
284 (defun main-thread-p (&optional (thread *current-thread*))
285 "True if THREAD, defaulting to current thread, is the main thread of the process."
286 (eq thread *initial-thread*))
288 (defmacro return-from-thread (values-form &key allow-exit)
289 "Unwinds from and terminates the current thread, with values from
290 VALUES-FORM as the results visible to JOIN-THREAD.
292 If current thread is the main thread of the process (see
293 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
294 terminating the main thread would terminate the entire process. If
295 ALLOW-EXIT is true, returning from the main thread is equivalent to
296 calling SB-EXT:EXIT with :CODE 0 and :ABORT NIL.
298 See also: ABORT-THREAD and SB-EXT:EXIT."
299 `(%return-from-thread (multiple-value-list ,values-form) ,allow-exit))
301 (defun %return-from-thread (values allow-exit)
302 (let ((self *current-thread*))
303 (cond ((main-thread-p self)
305 (error 'simple-thread-error
306 :format-control "~@<Tried to return ~S as values from main thread, ~
307 but exit was not allowed.~:@>"
308 :format-arguments (list values)
310 (sb!ext:exit :code 0))
312 (throw '%return-from-thread (values-list values))))))
314 (defun abort-thread (&key allow-exit)
315 "Unwinds from and terminates the current thread abnormally, causing
316 JOIN-THREAD on current thread to signal an error unless a
317 default-value is provided.
319 If current thread is the main thread of the process (see
320 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
321 terminating the main thread would terminate the entire process. If
322 ALLOW-EXIT is true, aborting the main thread is equivalent to calling
323 SB-EXT:EXIT code 1 and :ABORT NIL.
325 Invoking the initial ABORT restart estabilished by MAKE-THREAD is
326 equivalent to calling ABORT-THREAD in other than main threads.
327 However, whereas ABORT restart may be rebound, ABORT-THREAD always
328 unwinds the entire thread. (Behaviour of the initial ABORT restart for
329 main thread depends on the :TOPLEVEL argument to
330 SB-EXT:SAVE-LISP-AND-DIE.)
332 See also: RETURN-FROM-THREAD and SB-EXT:EXIT."
333 (let ((self *current-thread*))
334 (cond ((main-thread-p self)
336 (error 'simple-thread-error
337 :format-control "~@<Tried to abort initial thread, but ~
338 exit was not allowed.~:@>"))
339 (sb!ext:exit :code 1))
341 ;; We /could/ use TOPLEVEL-CATCHER or %END-OF-THE-WORLD as well, but
342 ;; this seems tidier. Those to are a bit too overloaded already.
343 (throw '%abort-thread t)))))
346 ;;;; Aliens, low level stuff
348 (define-alien-routine "kill_safely"
350 (os-thread #!-alpha unsigned #!+alpha unsigned-int)
353 (define-alien-routine "wake_thread"
355 (os-thread unsigned))
359 ;; FIXME it would be good to define what a thread id is or isn't
360 ;; (our current assumption is that it's a fixnum). It so happens
361 ;; that on Linux it's a pid, but it might not be on posix thread
363 (define-alien-routine ("create_thread" %create-thread)
364 unsigned (lisp-fun-address unsigned))
366 (declaim (inline %block-deferrable-signals))
367 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
372 (defun block-deferrable-signals ()
373 (%block-deferrable-signals 0 0))
377 (declaim (inline futex-wait %futex-wait futex-wake))
379 (define-alien-routine ("futex_wait" %futex-wait) int
380 (word unsigned) (old-value unsigned)
381 (to-sec long) (to-usec unsigned-long))
383 (defun futex-wait (word old to-sec to-usec)
385 (%futex-wait word old to-sec to-usec)))
387 (define-alien-routine "futex_wake"
388 int (word unsigned) (n unsigned-long))))
390 ;;; used by debug-int.lisp to access interrupt contexts
391 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
393 (defun sb!vm::current-thread-offset-sap (n)
394 (declare (type (unsigned-byte 27) n))
395 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
396 (* n sb!vm:n-word-bytes)))
399 (defun sb!vm::current-thread-offset-sap (n)
400 (declare (type (unsigned-byte 27) n))
401 (sb!vm::current-thread-offset-sap n))
404 (defmacro with-deadlocks ((thread lock &optional (timeout nil timeoutp)) &body forms)
405 (with-unique-names (n-thread n-lock new n-timeout)
406 `(let* ((,n-thread ,thread)
408 (,n-timeout ,(when timeoutp
410 (when sb!impl::*deadline*
411 sb!impl::*deadline-seconds*))))
413 ;; Using CONS tells the rest of the system there's a
414 ;; timeout in place, so it isn't considered a deadlock.
415 (cons ,n-timeout ,n-lock)
417 (declare (dynamic-extent ,new))
418 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
419 ;; in places where interrupts should already be disabled.
422 (setf (thread-waiting-for ,n-thread) ,new)
425 ;; Interrupt handlers and GC save and restore any
426 ;; previous wait marks using WITHOUT-DEADLOCKS below.
427 (setf (thread-waiting-for ,n-thread) nil)
428 (barrier (:write))))))
433 (setf (fdocumentation 'make-mutex 'function)
435 (fdocumentation 'mutex-name 'function)
436 "The name of the mutex. Setfable.")
438 #!+(and sb-thread sb-futex)
440 (define-structure-slot-addressor mutex-state-address
443 ;; Important: current code assumes these are fixnums or other
444 ;; lisp objects that don't need pinning.
445 (defconstant +lock-free+ 0)
446 (defconstant +lock-taken+ 1)
447 (defconstant +lock-contested+ 2))
449 (defun mutex-owner (mutex)
450 "Current owner of the mutex, NIL if the mutex is free. Naturally,
451 this is racy by design (another thread may acquire the mutex after
452 this function returns), it is intended for informative purposes. For
453 testing whether the current thread is holding a mutex see
455 ;; Make sure to get the current value.
456 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
458 (sb!ext:defglobal **deadlock-lock** nil)
460 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
461 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
462 (defun check-deadlock ()
463 (let* ((self *current-thread*)
466 (thread-waiting-for self))))
467 (labels ((detect-deadlock (lock)
468 (let ((other-thread (mutex-%owner lock)))
469 (cond ((not other-thread))
470 ((eq self other-thread)
472 (with-cas-lock ((symbol-value '**deadlock-lock**))
473 (prog1 (deadlock-chain self origin)
474 ;; We're now committed to signaling the
475 ;; error and breaking the deadlock, so
476 ;; mark us as no longer waiting on the
477 ;; lock. This ensures that a single
478 ;; deadlock is reported in only one
479 ;; thread, and that we don't look like
480 ;; we're waiting on the lock when print
481 ;; stuff -- because that may lead to
482 ;; further deadlock checking, in turn
483 ;; possibly leading to a bogus vicious
484 ;; metacycle on PRINT-OBJECT.
485 (setf (thread-waiting-for self) nil)))))
486 (error 'thread-deadlock
487 :thread *current-thread*
490 (let ((other-lock (progn
492 (thread-waiting-for other-thread))))
493 ;; If the thread is waiting with a timeout OTHER-LOCK
494 ;; is a cons, and we don't consider it a deadlock -- since
495 ;; it will time out on its own sooner or later.
496 (when (mutex-p other-lock)
497 (detect-deadlock other-lock)))))))
498 (deadlock-chain (thread lock)
499 (let* ((other-thread (mutex-owner lock))
500 (other-lock (when other-thread
502 (thread-waiting-for other-thread))))
503 (cond ((not other-thread)
504 ;; The deadlock is gone -- maybe someone unwound
505 ;; from the same deadlock already?
506 (return-from check-deadlock nil))
508 ;; There's a timeout -- no deadlock.
509 (return-from check-deadlock nil))
510 ((waitqueue-p other-lock)
512 (return-from check-deadlock nil))
513 ((eq self other-thread)
515 (list (list thread lock)))
518 (cons (cons thread lock)
519 (deadlock-chain other-thread other-lock))
520 ;; Again, the deadlock is gone?
521 (return-from check-deadlock nil)))))))
522 ;; Timeout means there is no deadlock
523 (when (mutex-p origin)
524 (detect-deadlock origin)
527 (defun %try-mutex (mutex new-owner)
528 (declare (type mutex mutex) (optimize (speed 3)))
530 (let ((old (mutex-%owner mutex)))
531 (when (eq new-owner old)
532 (error "Recursive lock attempt ~S." mutex))
535 (error "Strange deadlock on ~S in an unithreaded build?" mutex))
536 #!-(and sb-thread sb-futex)
538 ;; Don't even bother to try to CAS if it looks bad.
539 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
540 #!+(and sb-thread sb-futex)
541 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
542 (when (eql +lock-free+ (sb!ext:compare-and-swap (mutex-state mutex)
545 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
547 (bug "Old owner in free mutex: ~S" prev))
551 (defun %%wait-for-mutex (mutex new-owner to-sec to-usec stop-sec stop-usec)
552 (declare (type mutex mutex) (optimize (speed 3)))
554 (declare (ignore to-sec to-usec))
560 (not (mutex-%owner mutex)))
561 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil
563 do (return-from cas t)
566 (sb!ext:spin-loop-hint))
567 ;; Check for pending interrupts.
568 (with-interrupts nil)))
569 (declare (dynamic-extent #'cas))
570 (sb!impl::%%wait-for #'cas stop-sec stop-usec))
572 ;; This is a fairly direct translation of the Mutex 2 algorithm from
573 ;; "Futexes are Tricky" by Ulrich Drepper.
575 (when (eql +lock-free+ old)
576 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
579 (bug "Old owner in free mutex: ~S" prev))
580 (return-from %%wait-for-mutex t)))))
581 (prog ((old (sb!ext:compare-and-swap (mutex-state mutex)
582 +lock-free+ +lock-taken+)))
583 ;; Got it right off the bat?
586 ;; Mark it as contested, and sleep. (Exception: it was just released.)
587 (when (or (eql +lock-contested+ old)
588 (not (eql +lock-free+
589 (sb!ext:compare-and-swap
590 (mutex-state mutex) +lock-taken+ +lock-contested+))))
591 (when (eql 1 (with-pinned-objects (mutex)
592 (futex-wait (mutex-state-address mutex)
593 (get-lisp-obj-address +lock-contested+)
596 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
598 ;; 1 = ETIMEDOUT ***DONE***
599 ;; 2 = EINTR, a spurious wakeup
600 (return-from %%wait-for-mutex nil)))
601 ;; Try to get it, still marking it as contested.
603 (sb!ext:compare-and-swap (mutex-state mutex) +lock-free+ +lock-contested+))
604 ;; Update timeout if necessary.
606 (setf (values to-sec to-usec)
607 (sb!impl::relative-decoded-times stop-sec stop-usec)))
612 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
613 (with-deadlocks (self mutex timeout)
614 (with-interrupts (check-deadlock))
617 (return-from %wait-for-mutex
618 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
621 ;; FIXME: substract elapsed time from timeout...
622 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
623 (decode-timeout timeout))
626 (define-deprecated-function :early "1.0.37.33" get-mutex (grab-mutex)
627 (mutex &optional new-owner (waitp t) (timeout nil))
628 (declare (ignorable waitp timeout))
629 (let ((new-owner (or new-owner *current-thread*)))
630 (or (%try-mutex mutex new-owner)
633 (multiple-value-call #'%wait-for-mutex
634 mutex new-owner timeout (decode-timeout timeout))))))
636 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
638 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
639 the mutex is not immediately available, sleep until it is available.
641 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
642 GRAB-MUTEX should try to acquire the lock in the contested case.
644 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
645 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
646 that GRAB-MUTEX did -not- acquire the lock.
650 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
654 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
657 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
658 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
659 allows the call to be interrupted from sleep.
661 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
662 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
663 DEADLINE-TIMEOUT if the global deadline was due already on entering
666 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
669 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
672 (declare (ignorable waitp timeout))
673 (let ((self *current-thread*))
674 (or (%try-mutex mutex self)
677 (multiple-value-call #'%wait-for-mutex
678 mutex self timeout (decode-timeout timeout))))))
680 (defun release-mutex (mutex &key (if-not-owner :punt))
682 "Release MUTEX by setting it to NIL. Wake up threads waiting for
685 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
688 If the current thread is not the owner of the mutex then it silently
689 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
690 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
691 IF-NOT-OWNER is :FORCE)."
692 (declare (type mutex mutex))
693 ;; Order matters: set owner to NIL before releasing state.
694 (let* ((self *current-thread*)
695 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
696 (unless (eq self old-owner)
698 ((:punt) (return-from release-mutex nil))
700 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
702 (setf (mutex-%owner mutex) nil)
703 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
706 #!+(and sb-thread sb-futex)
708 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
709 ;; unsigned-byte type this can be used:
711 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
712 ;; (unless (eql old +lock-free+)
713 ;; (setf (mutex-state mutex) +lock-free+)
714 ;; (with-pinned-objects (mutex)
715 ;; (futex-wake (mutex-state-address mutex) 1))))
716 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
717 +lock-taken+ +lock-free+)))
718 (when (eql old +lock-contested+)
719 (sb!ext:compare-and-swap (mutex-state mutex)
720 +lock-contested+ +lock-free+)
721 (with-pinned-objects (mutex)
722 (futex-wake (mutex-state-address mutex) 1))))
726 ;;;; Waitqueues/condition variables
728 #!+(or (not sb-thread) sb-futex)
729 (defstruct (waitqueue (:constructor %make-waitqueue))
732 (name nil :type (or null thread-name))
733 #!+(and sb-thread sb-futex)
736 #!+(and sb-thread (not sb-futex))
738 (defstruct (waitqueue (:constructor %make-waitqueue))
741 (name nil :type (or null thread-name))
742 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
743 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
744 ;; lock. In most cases this should be uncontested thanks to the mutex --
745 ;; the only case where that might not be true is when CONDITION-WAIT
746 ;; unwinds and %WAITQUEUE-DROP is called.
751 (defun %waitqueue-enqueue (thread queue)
752 (setf (thread-waiting-for thread) queue)
753 (let ((head (waitqueue-%head queue))
754 (tail (waitqueue-%tail queue))
757 (setf (waitqueue-%head queue) new))
759 (setf (cdr tail) new))
760 (setf (waitqueue-%tail queue) new)
762 (defun %waitqueue-drop (thread queue)
763 (setf (thread-waiting-for thread) nil)
764 (let ((head (waitqueue-%head queue)))
765 (do ((list head (cdr list))
768 (eq (car list) thread))
770 (let ((rest (cdr list)))
772 (setf (cdr prev) rest))
774 (setf (waitqueue-%head queue) rest
777 (setf (waitqueue-%tail queue) prev)))))))
779 (defun %waitqueue-wakeup (queue n)
781 (loop while (plusp n)
782 for next = (let ((head (waitqueue-%head queue))
783 (tail (waitqueue-%tail queue)))
786 (setf (waitqueue-%head queue) nil
787 (waitqueue-%tail queue) nil)
788 (setf (waitqueue-%head queue) (cdr head)))
791 do (when (eq queue (sb!ext:compare-and-swap
792 (thread-waiting-for next) queue nil))
796 (def!method print-object ((waitqueue waitqueue) stream)
797 (print-unreadable-object (waitqueue stream :type t :identity t)
798 (format stream "~@[~A~]" (waitqueue-name waitqueue))))
800 (defun make-waitqueue (&key name)
802 "Create a waitqueue."
803 (%make-waitqueue :name name))
806 (setf (fdocumentation 'waitqueue-name 'function)
807 "The name of the waitqueue. Setfable.")
809 #!+(and sb-thread sb-futex)
810 (define-structure-slot-addressor waitqueue-token-address
814 (defun condition-wait (queue mutex &key timeout)
816 "Atomically release MUTEX and start waiting on QUEUE for till another thread
817 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
818 queue, at which point we re-acquire MUTEX and return T.
820 Spurious wakeups are possible.
822 If TIMEOUT is given, it is the maximum number of seconds to wait, including
823 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
824 wakeup and re-acquisition do not occur within the given time, returns NIL
825 without re-acquiring the mutex.
827 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
829 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
830 occurred the correct way to write code that uses CONDITION-WAIT is to loop
831 around the call, checking the the associated data:
834 (defvar *queue* (make-waitqueue))
835 (defvar *lock* (make-mutex))
838 (defun pop-data (&optional timeout)
841 do (or (condition-wait *queue* *lock* :timeout timeout)
842 ;; Lock not held, must unwind without touching *data*.
843 (return-from pop-data nil)))
847 (defun push-data (data)
850 (condition-notify *queue*)))
853 (declare (ignore queue))
856 (sb!ext:wait-for nil :timeout timeout) ; Yeah...
858 (let ((me *current-thread*))
860 (assert (eq me (mutex-%owner mutex)))
861 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
862 (decode-timeout timeout)
863 (let ((status :interrupted))
864 ;; Need to disable interrupts so that we don't miss grabbing the
865 ;; mutex on our way out.
871 (%with-cas-lock ((waitqueue-%owner queue))
872 (%waitqueue-enqueue me queue))
873 (release-mutex mutex)
875 (or (flet ((wakeup ()
877 (unless (eq queue (thread-waiting-for me))
879 (declare (dynamic-extent #'wakeup))
880 (allow-with-interrupts
881 (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
884 (with-pinned-objects (queue me)
885 (setf (waitqueue-token queue) me)
886 (release-mutex mutex)
887 ;; Now we go to sleep using futex-wait. If anyone else
888 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
889 ;; this comment, it will change the token, and so futex-wait
890 ;; returns immediately instead of sleeping. Ergo, no lost
891 ;; wakeup. We may get spurious wakeups, but that's ok.
893 (case (allow-with-interrupts
894 (futex-wait (waitqueue-token-address queue)
895 (get-lisp-obj-address me)
896 ;; our way of saying "no
904 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
906 ;; 2 = EINTR, a spurious wakeup
909 (%with-cas-lock ((waitqueue-%owner queue))
910 (if (eq queue (thread-waiting-for me))
911 (%waitqueue-drop me queue)
912 (unless (eq :ok status)
913 ;; CONDITION-NOTIFY thinks we've been woken up, but really
914 ;; we're unwinding. Wake someone else up.
915 (%waitqueue-wakeup queue 1))))
916 ;; Update timeout for mutex re-aquisition.
917 (when (and (eq :ok status) to-sec)
918 (setf (values to-sec to-usec)
919 (sb!impl::relative-decoded-times stop-sec stop-usec)))
920 ;; If we ran into deadline, try to get the mutex before
921 ;; signaling. If we don't unwind it will look like a normal
922 ;; return from user perspective.
923 (when (and (eq :timeout status) deadlinep)
924 (let ((got-it (%try-mutex mutex me)))
925 (allow-with-interrupts
928 (return-from condition-wait t))
930 ;; The deadline may have changed.
931 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
932 (decode-timeout timeout))
933 (setf status :ok))))))
934 ;; Re-acquire the mutex for normal return.
935 (when (eq :ok status)
936 (unless (or (%try-mutex mutex me)
937 (allow-with-interrupts
938 (%wait-for-mutex mutex me timeout
940 stop-sec stop-usec deadlinep)))
941 (setf status :timeout)))))
943 (unless (eq :timeout status)
944 ;; The only case we return normally without re-acquiring the
945 ;; mutex is when there is a :TIMEOUT that runs out.
946 (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
948 (defun condition-notify (queue &optional (n 1))
950 "Notify N threads waiting on QUEUE.
952 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
953 must be held by this thread during this call."
955 (declare (ignore queue n))
957 (error "Not supported in unithread builds.")
959 (declare (type (and fixnum (integer 1)) n))
960 (/show0 "Entering CONDITION-NOTIFY")
964 (with-cas-lock ((waitqueue-%owner queue))
965 (%waitqueue-wakeup queue n))
968 ;; No problem if >1 thread notifies during the comment in condition-wait:
969 ;; as long as the value in queue-data isn't the waiting thread's id, it
970 ;; matters not what it is -- using the queue object itself is handy.
972 ;; XXX we should do something to ensure that the result of this setf
973 ;; is visible to all CPUs.
975 ;; ^-- surely futex_wake() involves a memory barrier?
976 (setf (waitqueue-token queue) queue)
977 (with-pinned-objects (queue)
978 (futex-wake (waitqueue-token-address queue) n)))))
980 (defun condition-broadcast (queue)
982 "Notify all threads waiting on QUEUE.
984 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
985 must be held by this thread during this call."
986 (condition-notify queue
987 ;; On a 64-bit platform truncating M-P-F to an int
988 ;; results in -1, which wakes up only one thread.
990 most-positive-fixnum)))
995 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
997 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
998 should be considered an implementation detail, and may change in the
1000 (name nil :type (or null thread-name))
1001 (%count 0 :type (integer 0))
1002 (waitcount 0 :type sb!vm:word)
1003 (mutex (make-mutex))
1004 (queue (make-waitqueue)))
1006 (setf (fdocumentation 'semaphore-name 'function)
1007 "The name of the semaphore INSTANCE. Setfable.")
1009 (defstruct (semaphore-notification (:constructor make-semaphore-notification ())
1012 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
1013 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
1014 multiple threads are using the same notification object in parallel."
1015 (%status nil :type boolean))
1017 (setf (fdocumentation 'make-semaphore-notification 'function)
1018 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
1021 (declaim (inline semaphore-notification-status))
1022 (defun semaphore-notification-status (semaphore-notification)
1024 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
1025 SEMAPHORE-NOTICATION has succeeded since the notification object was created
1028 (semaphore-notification-%status semaphore-notification))
1030 (declaim (inline clear-semaphore-notification))
1031 (defun clear-semaphore-notification (semaphore-notification)
1033 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
1034 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
1036 (setf (semaphore-notification-%status semaphore-notification) nil)))
1038 (declaim (inline semaphore-count))
1039 (defun semaphore-count (instance)
1041 "Returns the current count of the semaphore INSTANCE."
1043 (semaphore-%count instance))
1045 (defun make-semaphore (&key name (count 0))
1047 "Create a semaphore with the supplied COUNT and NAME."
1048 (%make-semaphore name count))
1050 (defun wait-on-semaphore (semaphore &key timeout notification)
1052 "Decrement the count of SEMAPHORE if the count would not be negative. Else
1053 blocks until the semaphore can be decremented. Returns T on success.
1055 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
1056 cannot be decremented in that time, returns NIL without decrementing the
1059 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
1060 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
1061 decrements the count, the status is set to T."
1062 (when (and notification (semaphore-notification-status notification))
1063 (with-simple-restart (continue "Clear notification status and continue.")
1064 (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
1065 'wait-on-semaphore semaphore))
1066 (clear-semaphore-notification notification))
1067 ;; A more direct implementation based directly on futexes should be
1070 ;; We need to disable interrupts so that we don't forget to
1071 ;; decrement the waitcount (which would happen if an asynch
1072 ;; interrupt should catch us on our way out from the loop.)
1074 ;; FIXME: No timeout on initial mutex acquisition.
1075 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1076 ;; Quick check: is it positive? If not, enter the wait loop.
1077 (let ((count (semaphore-%count semaphore)))
1078 (cond ((plusp count)
1079 (setf (semaphore-%count semaphore) (1- count))
1081 (setf (semaphore-notification-%status notification) t)))
1085 ;; Need to use ATOMIC-INCF despite the lock, because on our
1086 ;; way out from here we might not be locked anymore -- so
1087 ;; another thread might be tweaking this in parallel using
1088 ;; ATOMIC-DECF. No danger over overflow, since there it
1089 ;; at most one increment per thread waiting on the semaphore.
1090 (sb!ext:atomic-incf (semaphore-waitcount semaphore))
1091 (loop until (plusp (setf count (semaphore-%count semaphore)))
1092 do (or (condition-wait (semaphore-queue semaphore)
1093 (semaphore-mutex semaphore)
1095 (return-from wait-on-semaphore nil)))
1096 (setf (semaphore-%count semaphore) (1- count))
1098 (setf (semaphore-notification-%status notification) t)))
1099 ;; Need to use ATOMIC-DECF as we may unwind without the lock
1101 (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
1104 (defun try-semaphore (semaphore &optional (n 1) notification)
1106 "Try to decrement the count of SEMAPHORE by N. If the count were to
1107 become negative, punt and return NIL, otherwise return true.
1109 If NOTIFICATION is given it must be a semaphore notification object
1110 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1111 the status is set to T."
1112 (declare (type (integer 1) n))
1113 (when (and notification (semaphore-notification-status notification))
1114 (with-simple-restart (continue "Clear notification status and continue.")
1115 (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
1116 'try-semaphore semaphore))
1117 (clear-semaphore-notification notification))
1118 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1119 (let ((new-count (- (semaphore-%count semaphore) n)))
1120 (when (not (minusp new-count))
1121 (setf (semaphore-%count semaphore) new-count)
1123 (setf (semaphore-notification-%status notification) t))
1124 ;; FIXME: We don't actually document this -- should we just
1125 ;; return T, or document new count as the return?
1128 (defun signal-semaphore (semaphore &optional (n 1))
1130 "Increment the count of SEMAPHORE by N. If there are threads waiting
1131 on this semaphore, then N of them is woken up."
1132 (declare (type (integer 1) n))
1133 ;; Need to disable interrupts so that we don't lose a wakeup after
1134 ;; we have incremented the count.
1135 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1136 (let ((waitcount (semaphore-waitcount semaphore))
1137 (count (incf (semaphore-%count semaphore) n)))
1138 (when (plusp waitcount)
1139 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1142 ;;;; Job control, independent listeners
1145 (lock (make-mutex :name "session lock"))
1147 (interactive-threads nil)
1148 (interactive-threads-queue (make-waitqueue)))
1150 (defvar *session* nil)
1152 ;;; The debugger itself tries to acquire the session lock, don't let
1153 ;;; funny situations (like getting a sigint while holding the session
1154 ;;; lock) occur. At the same time we need to allow interrupts while
1155 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1156 ;;; be interruptible.
1158 ;;; Take care: we sometimes need to obtain the session lock while
1159 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1160 ;;; _after_ getting a session lock! (Deadlock risk.)
1162 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1164 (defmacro with-session-lock ((session) &body body)
1165 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1168 (defun new-session ()
1169 (make-session :threads (list *current-thread*)
1170 :interactive-threads (list *current-thread*)))
1172 (defun init-job-control ()
1173 (/show0 "Entering INIT-JOB-CONTROL")
1174 (setf *session* (new-session))
1175 (/show0 "Exiting INIT-JOB-CONTROL"))
1177 (defun %delete-thread-from-session (thread session)
1178 (with-session-lock (session)
1179 (setf (session-threads session)
1180 (delete thread (session-threads session))
1181 (session-interactive-threads session)
1182 (delete thread (session-interactive-threads session)))))
1184 (defun call-with-new-session (fn)
1185 (%delete-thread-from-session *current-thread* *session*)
1186 (let ((*session* (new-session)))
1189 (defmacro with-new-session (args &body forms)
1190 (declare (ignore args)) ;for extensibility
1191 (sb!int:with-unique-names (fb-name)
1192 `(labels ((,fb-name () ,@forms))
1193 (call-with-new-session (function ,fb-name)))))
1195 ;;; Remove thread from its session, if it has one.
1197 (defun handle-thread-exit (thread)
1198 (/show0 "HANDLING THREAD EXIT")
1199 (when *exit-in-process*
1201 ;; Lisp-side cleanup
1202 (with-all-threads-lock
1203 (setf (thread-%alive-p thread) nil)
1204 (setf (thread-os-thread thread) nil)
1205 (setq *all-threads* (delete thread *all-threads*))
1207 (%delete-thread-from-session thread *session*))))
1209 (defun %exit-other-threads ()
1210 ;; Grabbing this lock prevents new threads from
1211 ;; being spawned, and guarantees that *ALL-THREADS*
1213 (with-deadline (:seconds nil :override t)
1214 (grab-mutex *make-thread-lock*)
1215 (let ((timeout sb!ext:*exit-timeout*)
1216 (code *exit-in-process*)
1217 (current *current-thread*)
1220 (dolist (thread (list-all-threads))
1221 (cond ((eq thread current))
1222 ((main-thread-p thread)
1227 (terminate-thread thread)
1228 (push thread joinees))
1229 (interrupt-thread-error ())))))
1230 (with-progressive-timeout (time-left :seconds timeout)
1231 (dolist (thread joinees)
1232 (join-thread thread :default t :timeout (time-left)))
1233 ;; Need to defer till others have joined, because when main
1234 ;; thread exits, we're gone. Can't use TERMINATE-THREAD -- would
1235 ;; get the exit code wrong.
1241 (setf *exit-in-process* (list code))
1242 (throw 'sb!impl::%end-of-the-world t)))
1243 (interrupt-thread-error ()))
1244 ;; Normally this never finishes, as once the main-thread unwinds we
1245 ;; exit with the right code, but if times out before that happens,
1246 ;; we will exit after returning -- or rathe racing the main thread
1247 ;; to calling OS-EXIT.
1248 (join-thread main :default t :timeout (time-left)))))))
1250 (defun terminate-session ()
1252 "Kill all threads in session except for this one. Does nothing if current
1253 thread is not the foreground thread."
1254 ;; FIXME: threads created in other threads may escape termination
1256 (with-session-lock (*session*)
1257 (and (eq *current-thread*
1258 (car (session-interactive-threads *session*)))
1259 (session-threads *session*)))))
1260 ;; do the kill after dropping the mutex; unwind forms in dying
1261 ;; threads may want to do session things
1262 (dolist (thread to-kill)
1263 (unless (eq thread *current-thread*)
1264 ;; terminate the thread but don't be surprised if it has
1265 ;; exited in the meantime
1266 (handler-case (terminate-thread thread)
1267 (interrupt-thread-error ()))))))
1269 ;;; called from top of invoke-debugger
1270 (defun debugger-wait-until-foreground-thread (stream)
1271 "Returns T if thread had been running in background, NIL if it was
1273 (declare (ignore stream))
1277 (with-session-lock (*session*)
1278 (not (member *current-thread*
1279 (session-interactive-threads *session*))))
1282 (defun get-foreground ()
1285 (let ((was-foreground t))
1287 (/show0 "Looping in GET-FOREGROUND")
1288 (with-session-lock (*session*)
1289 (let ((int-t (session-interactive-threads *session*)))
1290 (when (eq (car int-t) *current-thread*)
1291 (unless was-foreground
1292 (format *query-io* "Resuming thread ~A~%" *current-thread*))
1293 (return-from get-foreground t))
1294 (setf was-foreground nil)
1295 (unless (member *current-thread* int-t)
1296 (setf (cdr (last int-t))
1297 (list *current-thread*)))
1299 (session-interactive-threads-queue *session*)
1300 (session-lock *session*)))))))
1302 (defun release-foreground (&optional next)
1304 "Background this thread. If NEXT is supplied, arrange for it to
1305 have the foreground next."
1306 #!-sb-thread (declare (ignore next))
1309 (with-session-lock (*session*)
1310 (when (rest (session-interactive-threads *session*))
1311 (setf (session-interactive-threads *session*)
1312 (delete *current-thread* (session-interactive-threads *session*))))
1314 (setf (session-interactive-threads *session*)
1316 (delete next (session-interactive-threads *session*)))))
1317 (condition-broadcast (session-interactive-threads-queue *session*))))
1319 (defun foreground-thread ()
1320 (car (session-interactive-threads *session*)))
1322 (defun make-listener-thread (tty-name)
1323 (assert (probe-file tty-name))
1324 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1325 (out (sb!unix:unix-dup in))
1326 (err (sb!unix:unix-dup in)))
1327 (labels ((thread-repl ()
1328 (sb!unix::unix-setsid)
1329 (let* ((sb!impl::*stdin*
1330 (make-fd-stream in :input t :buffering :line
1333 (make-fd-stream out :output t :buffering :line
1336 (make-fd-stream err :output t :buffering :line
1339 (make-fd-stream err :input t :output t
1342 (sb!impl::*descriptor-handlers* nil))
1343 (with-new-session ()
1345 (sb!impl::toplevel-repl nil)
1346 (sb!int:flush-standard-output-streams))))))
1347 (make-thread #'thread-repl))))
1353 (defun initial-thread-function-trampoline
1354 (thread setup-sem real-function arguments arg1 arg2 arg3)
1355 ;; In time we'll move some of the binding presently done in C here
1358 ;; KLUDGE: Here we have a magic list of variables that are not
1359 ;; thread-safe for one reason or another. As people report problems
1360 ;; with the thread safety of certain variables, (e.g. "*print-case* in
1361 ;; multiple threads broken", sbcl-devel 2006-07-14), we add a few more
1362 ;; bindings here. The Right Thing is probably some variant of
1363 ;; Allegro's *cl-default-special-bindings*, as that is at least
1364 ;; accessible to users to secure their own libraries.
1365 ;; --njf, 2006-07-15
1367 ;; As it is, this lambda must not cons until we are ready to run
1368 ;; GC. Be very careful.
1369 (let* ((*current-thread* thread)
1370 (*restart-clusters* nil)
1371 (*handler-clusters* (sb!kernel::initial-handler-clusters))
1372 (*condition-restarts* nil)
1373 (*exit-in-process* nil)
1374 (sb!impl::*deadline* nil)
1375 (sb!impl::*deadline-seconds* nil)
1376 (sb!impl::*step-out* nil)
1377 ;; internal printer variables
1378 (sb!impl::*previous-case* nil)
1379 (sb!impl::*previous-readtable-case* nil)
1380 (sb!impl::*internal-symbol-output-fun* nil)
1381 (sb!impl::*descriptor-handlers* nil)) ; serve-event
1383 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1384 (setf (thread-os-thread thread) (current-thread-os-thread))
1385 (with-mutex ((thread-result-lock thread))
1386 (with-all-threads-lock
1387 (push thread *all-threads*))
1388 (with-session-lock (*session*)
1389 (push thread (session-threads *session*)))
1390 (setf (thread-%alive-p thread) t)
1391 (when setup-sem (signal-semaphore setup-sem))
1392 ;; Using handling-end-of-the-world would be a bit tricky
1393 ;; due to other catches and interrupts, so we essentially
1394 ;; re-implement it here. Once and only once more.
1395 (catch 'sb!impl::toplevel-catcher
1396 (catch 'sb!impl::%end-of-the-world
1397 (catch '%abort-thread
1398 (with-simple-restart
1399 (abort "~@<Abort thread (~A)~@:>" *current-thread*)
1402 (with-local-interrupts
1403 (setf *gc-inhibit* nil) ;for foreign callbacks
1404 (sb!unix::unblock-deferrable-signals)
1405 (setf (thread-result thread)
1408 (multiple-value-list
1410 (catch '%return-from-thread
1411 (if (listp arguments)
1412 (apply real-function arguments)
1413 (funcall real-function arg1 arg2 arg3)))
1414 (when *exit-in-process*
1415 (sb!impl::call-exit-hooks)))))
1417 (sb!kernel::gc-safepoint))))
1418 ;; We're going down, can't handle interrupts
1419 ;; sanely anymore. GC remains enabled.
1420 (block-deferrable-signals)
1421 ;; We don't want to run interrupts in a dead
1422 ;; thread when we leave WITHOUT-INTERRUPTS.
1423 ;; This potentially causes important
1424 ;; interupts to be lost: SIGINT comes to
1426 (setq *interrupt-pending* nil)
1428 (setq *thruption-pending* nil)
1429 (handle-thread-exit thread)))))))))
1432 (defun make-thread (function &key name arguments ephemeral)
1434 "Create a new thread of NAME that runs FUNCTION with the argument
1435 list designator provided (defaults to no argument). Thread exits when
1436 the function returns. The return values of FUNCTION are kept around
1437 and can be retrieved by JOIN-THREAD.
1439 Invoking the initial ABORT restart estabilished by MAKE-THREAD
1440 terminates the thread.
1442 See also: RETURN-FROM-THREAD, ABORT-THREAD."
1443 #!-sb-thread (declare (ignore function name arguments ephemeral))
1444 #!-sb-thread (error "Not supported in unithread builds.")
1445 #!+sb-thread (assert (or (atom arguments)
1446 (null (cdr (last arguments))))
1448 "Argument passed to ~S, ~S, is an improper list."
1449 'make-thread arguments)
1451 (let ((thread (%make-thread :name name :%ephemeral-p ephemeral)))
1452 (with-mutex (*make-thread-lock*)
1453 (let* ((setup-sem (make-semaphore :name "Thread setup semaphore"))
1454 (real-function (coerce function 'function))
1455 (arguments (if (listp arguments)
1459 (named-lambda initial-thread-function ()
1460 ;; As it is, this lambda must not cons until we are ready
1461 ;; to run GC. Be very careful.
1462 (initial-thread-function-trampoline
1463 thread setup-sem real-function arguments nil nil nil))))
1464 ;; If the starting thread is stopped for gc before it signals the
1465 ;; semaphore then we'd be stuck.
1466 (assert (not *gc-inhibit*))
1467 ;; Keep INITIAL-FUNCTION pinned until the child thread is
1468 ;; initialized properly. Wrap the whole thing in
1469 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1472 (with-pinned-objects (initial-function)
1474 (%create-thread (get-lisp-obj-address initial-function)))
1476 (wait-on-semaphore setup-sem))))))
1477 (or thread (error "Could not create a new thread."))))
1479 (defun join-thread (thread &key (default nil defaultp) timeout)
1481 "Suspend current thread until THREAD exits. Return the result values
1482 of the thread function.
1484 If the thread does not exit normally within TIMEOUT seconds return
1485 DEFAULT if given, or else signal JOIN-THREAD-ERROR.
1487 Trying to join the main thread will cause JOIN-THREAD to block until
1488 TIMEOUT occurs or the process exits: when main thread exits, the
1489 entire process exits.
1491 NOTE: Return convention in case of a timeout is exprimental and
1493 (let ((lock (thread-result-lock thread))
1499 (allow-with-interrupts
1500 ;; Don't use the timeout if the thread is not alive anymore.
1501 (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
1502 (cond ((car (thread-result thread))
1503 (return-from join-thread
1504 (values-list (cdr (thread-result thread)))))
1506 (return-from join-thread default))
1508 (setf problem :abort)))
1510 (return-from join-thread default)))
1512 (release-mutex lock))))
1513 (error 'join-thread-error :thread thread :problem problem)))
1515 (defun destroy-thread (thread)
1517 "Deprecated. Same as TERMINATE-THREAD."
1518 (terminate-thread thread))
1521 (defun enter-foreign-callback (arg1 arg2 arg3)
1522 (initial-thread-function-trampoline
1523 (make-foreign-thread :name "foreign callback")
1524 nil #'sb!alien::enter-alien-callback t arg1 arg2 arg3))
1526 (defmacro with-interruptions-lock ((thread) &body body)
1527 `(with-system-mutex ((thread-interruptions-lock ,thread))
1530 ;;; Called from the signal handler.
1531 #!-(or sb-thruption win32)
1532 (defun run-interruption ()
1533 (let ((interruption (with-interruptions-lock (*current-thread*)
1534 (pop (thread-interruptions *current-thread*)))))
1535 ;; If there is more to do, then resignal and let the normal
1536 ;; interrupt deferral mechanism take care of the rest. From the
1537 ;; OS's point of view the signal we are in the handler for is no
1538 ;; longer pending, so the signal will not be lost.
1539 (when (thread-interruptions *current-thread*)
1540 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1542 (funcall interruption))))
1545 (defun run-interruption ()
1546 (in-interruption () ;the non-thruption code does this in the signal handler
1547 (let ((interruption (with-interruptions-lock (*current-thread*)
1548 (pop (thread-interruptions *current-thread*)))))
1550 (funcall interruption)
1551 ;; I tried implementing this function as an explicit LOOP, because
1552 ;; if we are currently processing the thruption queue, why not do
1553 ;; all of them in one go instead of one-by-one?
1555 ;; I still think LOOPing would be basically the right thing
1556 ;; here. But suppose some interruption unblocked deferrables.
1557 ;; Will the next one be happy with that? The answer is "no", at
1558 ;; least in the sense that there are tests which check that
1559 ;; deferrables are blocked at the beginning of a thruption, and
1560 ;; races that make those tests fail. Whether the tests are
1561 ;; misguided or not, it seems easier/cleaner to loop implicitly
1562 ;; -- and it's also what AK had implemented in the first place.
1564 ;; The implicit loop is achieved by returning to C, but having C
1565 ;; call back to us immediately. The runtime will reset the sigmask
1566 ;; in the mean time.
1568 (setf *thruption-pending* t)))))
1570 (defun interrupt-thread (thread function)
1572 "Interrupt THREAD and make it run FUNCTION.
1574 The interrupt is asynchronous, and can occur anywhere with the exception of
1575 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1577 FUNCTION is called with interrupts disabled, under
1578 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1579 enable interrupts internally, in most cases FUNCTION should either enter
1580 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1581 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1583 When a thread receives multiple interrupts, they are executed in the order
1584 they were sent -- first in, first out.
1586 This means that a great degree of care is required to use INTERRUPT-THREAD
1587 safely and sanely in a production environment. The general recommendation is
1588 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1589 entirely from production environments -- it is simply exceedingly hard to use
1592 With those caveats in mind, what you need to know when using it:
1594 * If calling FUNCTION causes a non-local transfer of control (ie. an
1595 unwind), all normal cleanup forms will be executed.
1597 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1598 it is just as if that had happened due to a regular GO, THROW, or
1599 RETURN-FROM: the interrupted cleanup form and those following it in the
1600 same UNWIND-PROTECT do not get executed.
1602 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1603 frankly an unreasonable expectation for third party libraries, especially
1604 given that asynch-unwind-safety does not compose: a function calling
1605 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1607 This means that in order for an asych unwind to be safe, the entire
1608 callstack at the point of interruption needs to be asynch-unwind-safe.
1610 * In addition to asynch-unwind-safety you must consider the issue of
1611 re-entrancy. INTERRUPT-THREAD can cause function that are never normally
1612 called recursively to be re-entered during their dynamic contour,
1613 which may cause them to misbehave. (Consider binding of special variables,
1614 values of global variables, etc.)
1616 Take togather, these two restrict the \"safe\" things to do using
1617 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1618 interactive development use is using it to force entry to debugger to inspect
1619 the state of a thread:
1621 (interrupt-thread thread #'break)
1623 Short version: be careful out there."
1624 #!+(and (not sb-thread) win32)
1625 #!+(and (not sb-thread) win32)
1626 (declare (ignore thread))
1627 (with-interrupt-bindings
1628 (with-interrupts (funcall function)))
1629 #!-(and (not sb-thread) win32)
1630 (let ((os-thread (thread-os-thread thread)))
1631 (cond ((not os-thread)
1632 (error 'interrupt-thread-error :thread thread))
1634 (with-interruptions-lock (thread)
1635 ;; Append to the end of the interruptions queue. It's
1636 ;; O(N), but it does not hurt to slow interruptors down a
1637 ;; bit when the queue gets long.
1638 (setf (thread-interruptions thread)
1639 (append (thread-interruptions thread)
1642 (allow-with-interrupts
1643 (funcall function))))))))
1644 (when (minusp (wake-thread os-thread))
1645 (error 'interrupt-thread-error :thread thread))))))
1647 (defun terminate-thread (thread)
1649 "Terminate the thread identified by THREAD, by interrupting it and
1650 causing it to call SB-EXT:ABORT-THREAD with :ALLOW-EXIT T.
1652 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that
1653 eg. thread executing
1658 (setf foo (get-foo))
1661 ;; An interrupt occurring inside the cleanup clause
1662 ;; will cause cleanups from the current UNWIND-PROTECT
1664 (release-foo foo))))
1666 might miss calling RELEASE-FOO despite GET-FOO having returned true if
1667 the interrupt occurs inside the cleanup clause, eg. during execution
1670 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need
1671 to use WITHOUT-INTERRUPTS:
1674 (sb-sys:without-interrupts
1677 (setf foo (sb-sys:allow-with-interrupts
1679 (sb-sys:with-local-interrupts
1682 (release-foo foo)))))
1684 Since most libraries using UNWIND-PROTECT do not do this, you should never
1685 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1686 (interrupt-thread thread (lambda () (abort-thread :allow-exit t))))
1688 (define-alien-routine "thread_yield" int)
1691 (setf (fdocumentation 'thread-yield 'function)
1692 "Yield the processor to other threads.")
1694 ;;; internal use only. If you think you need to use these, either you
1695 ;;; are an SBCL developer, are doing something that you should discuss
1696 ;;; with an SBCL developer first, or are doing something that you
1697 ;;; should probably discuss with a professional psychiatrist first
1700 (defun %thread-sap (thread)
1701 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1702 (target (thread-os-thread thread)))
1704 (when (sap= thread-sap (int-sap 0)) (return nil))
1705 (let ((os-thread (sap-ref-word thread-sap
1706 (* sb!vm:n-word-bytes
1707 sb!vm::thread-os-thread-slot))))
1708 (when (= os-thread target) (return thread-sap))
1710 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1711 sb!vm::thread-next-slot)))))))
1713 (defun %symbol-value-in-thread (symbol thread)
1714 ;; Prevent the thread from dying completely while we look for the TLS
1716 (with-all-threads-lock
1717 (if (thread-alive-p thread)
1718 (let* ((offset (sb!kernel:get-lisp-obj-address
1719 (sb!vm::symbol-tls-index symbol)))
1720 (obj (sap-ref-lispobj (%thread-sap thread) offset))
1721 (tl-val (sb!kernel:get-lisp-obj-address obj)))
1722 (cond ((zerop offset)
1723 (values nil :no-tls-value))
1724 ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1725 (eql tl-val sb!vm:unbound-marker-widetag))
1726 (values nil :unbound-in-thread))
1729 (values nil :thread-dead))))
1731 (defun %set-symbol-value-in-thread (symbol thread value)
1732 (with-pinned-objects (value)
1733 ;; Prevent the thread from dying completely while we look for the TLS
1735 (with-all-threads-lock
1736 (if (thread-alive-p thread)
1737 (let ((offset (sb!kernel:get-lisp-obj-address
1738 (sb!vm::symbol-tls-index symbol))))
1739 (cond ((zerop offset)
1740 (values nil :no-tls-value))
1742 (setf (sap-ref-lispobj (%thread-sap thread) offset)
1744 (values value :ok))))
1745 (values nil :thread-dead)))))
1747 (define-alien-variable tls-index-start unsigned-int)
1749 ;; Get values from the TLS area of the current thread.
1750 (defun %thread-local-references ()
1752 (let ((sap (%thread-sap *current-thread*)))
1753 (loop for index from tls-index-start
1754 below (symbol-value 'sb!vm::*free-tls-index*)
1755 for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1756 for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1758 (typep obj '(or fixnum character))
1760 '(#.sb!vm:no-tls-value-marker-widetag
1761 #.sb!vm:unbound-marker-widetag))
1762 (member obj seen :test #'eq))
1763 collect obj into seen
1764 finally (return seen))))))
1766 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1767 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1770 If the value cannot be retrieved (because the thread has exited or because it
1771 has no local binding for NAME) and ERRORP is true signals an error of type
1772 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1773 NIL, and a secondary value of NIL.
1775 Can also be used with SETF to change the thread-local value of SYMBOL.
1777 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1778 mechanism for inter-thread communication."
1779 (declare (symbol symbol) (thread thread))
1781 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1785 (error 'symbol-value-in-thread-error
1788 :info (list :read status))
1792 (values (symbol-value symbol) t)
1794 (error 'symbol-value-in-thread-error
1797 :info (list :read :unbound-in-thread))
1800 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1801 (declare (symbol symbol) (thread thread))
1803 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1807 (error 'symbol-value-in-thread-error
1810 :info (list :write status))
1814 (values (setf (symbol-value symbol) value) t)
1816 (error 'symbol-value-in-thread-error
1819 :info (list :write :unbound-in-thread))
1822 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1823 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1828 (defun thread-stepping ()
1830 (sap-ref-word (current-thread-sap)
1831 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1833 (defun (setf thread-stepping) (value)
1834 (setf (sap-ref-word (current-thread-sap)
1835 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1836 (get-lisp-obj-address value)))