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 thread-deadlock (thread-error)
78 ((cycle :initarg :cycle :reader thread-deadlock-cycle))
80 (lambda (condition stream)
81 (let* ((*print-circle* t)
82 (cycle (thread-deadlock-cycle condition))
84 (format stream "Deadlock cycle detected:~%")
85 (loop for part = (pop cycle)
87 do (format stream " ~S~% waited for:~% ~S~% owned by:~%"
90 (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."))))))
114 "Signalled when SYMBOL-VALUE-IN-THREAD or its SETF version fails due to eg.
115 the symbol not having a thread-local value, or the target thread having
116 exited. The offending symbol can be accessed using CELL-ERROR-NAME, and the
117 offending thread using THREAD-ERROR-THREAD."))
119 (define-condition join-thread-error (thread-error)
120 ((problem :initarg :problem :reader join-thread-problem))
121 (:report (lambda (c s)
122 (ecase (join-thread-problem c)
124 (format s "Joining thread failed: thread ~A ~
125 did not return normally."
126 (thread-error-thread c)))
128 (format s "Joining thread timed out: thread ~A ~
129 did not exit in time."
130 (thread-error-thread c))))))
133 "Signalled when joining a thread fails due to abnormal exit of the thread
134 to be joined. The offending thread can be accessed using
135 THREAD-ERROR-THREAD."))
137 (define-deprecated-function :late "1.0.29.17" join-thread-error-thread thread-error-thread
139 (thread-error-thread condition))
141 (define-condition interrupt-thread-error (thread-error) ()
142 (:report (lambda (c s)
143 (format s "Interrupt thread failed: thread ~A has exited."
144 (thread-error-thread c))))
147 "Signalled when interrupting a thread fails because the thread has already
148 exited. The offending thread can be accessed using THREAD-ERROR-THREAD."))
150 (define-deprecated-function :late "1.0.29.17" interrupt-thread-error-thread thread-error-thread
152 (thread-error-thread condition))
154 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
155 ;;; necessary because threads are only supported with the conservative
156 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
157 ;;; are treated as references.
159 ;;; set the doc here because in early-thread FDOCUMENTATION is not
162 (setf (fdocumentation '*current-thread* 'variable)
163 "Bound in each thread to the thread itself.")
167 (fdocumentation 'thread-name 'function)
168 "Name of the thread. Can be assigned to using SETF. Thread names can be
169 arbitrary printable objects, and need not be unique.")
171 (def!method print-object ((thread thread) stream)
172 (print-unreadable-object (thread stream :type t :identity t)
173 (let* ((cookie (list thread))
174 (info (if (thread-alive-p thread)
177 (join-thread thread :default cookie))))
178 (state (if (eq :running info)
181 (thread-waiting-for thread))))
184 (list "waiting on:" (cdr thing)
185 "timeout: " (car thing)))
189 (list "waiting on:" thing))))
190 (if (eq cookie (car info))
193 (values (when (eq :finished state)
197 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
203 (defun print-lock (lock name owner stream)
204 (let ((*print-circle* t))
205 (print-unreadable-object (lock stream :type t :identity (not name))
207 (format stream "~@[~S ~]~2I~_owner: ~S" name owner)
208 (format stream "~@[~S ~](free)" name)))))
210 (def!method print-object ((mutex mutex) stream)
211 (print-lock mutex (mutex-name mutex) (mutex-owner mutex) stream))
213 (defun thread-alive-p (thread)
215 "Return T if THREAD is still alive. Note that the return value is
216 potentially stale even before the function returns, as the thread may exit at
218 (thread-%alive-p thread))
220 ;; A thread is eligible for gc iff it has finished and there are no
221 ;; more references to it. This list is supposed to keep a reference to
222 ;; all running threads.
223 (defvar *all-threads* ())
224 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
226 (defvar *default-alloc-signal* nil)
228 (defmacro with-all-threads-lock (&body body)
229 `(with-system-mutex (*all-threads-lock*)
232 (defun list-all-threads ()
234 "Return a list of the live threads. Note that the return value is
235 potentially stale even before the function returns, as new threads may be
236 created and old ones may exit at any time."
237 (with-all-threads-lock
238 (copy-list *all-threads*)))
240 (declaim (inline current-thread-sap))
241 (defun current-thread-sap ()
242 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
244 (declaim (inline current-thread-os-thread))
245 (defun current-thread-os-thread ()
247 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
251 (defun init-initial-thread ()
252 (/show0 "Entering INIT-INITIAL-THREAD")
253 (let ((initial-thread (%make-thread :name "initial thread"
255 :os-thread (current-thread-os-thread))))
256 (setq *current-thread* initial-thread)
257 ;; Either *all-threads* is empty or it contains exactly one thread
258 ;; in case we are in reinit since saving core with multiple
259 ;; threads doesn't work.
260 (setq *all-threads* (list initial-thread))))
263 ;;;; Aliens, low level stuff
265 (define-alien-routine "kill_safely"
267 (os-thread #!-alpha unsigned-long #!+alpha unsigned-int)
272 ;; FIXME it would be good to define what a thread id is or isn't
273 ;; (our current assumption is that it's a fixnum). It so happens
274 ;; that on Linux it's a pid, but it might not be on posix thread
276 (define-alien-routine ("create_thread" %create-thread)
277 unsigned-long (lisp-fun-address unsigned-long))
279 (declaim (inline %block-deferrable-signals))
280 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
282 (where sb!alien:unsigned-long)
283 (old sb!alien:unsigned-long))
285 (defun block-deferrable-signals ()
286 (%block-deferrable-signals 0 0))
290 (declaim (inline futex-wait %futex-wait futex-wake))
292 (define-alien-routine ("futex_wait" %futex-wait)
293 int (word unsigned-long) (old-value unsigned-long)
294 (to-sec long) (to-usec unsigned-long))
296 (defun futex-wait (word old to-sec to-usec)
298 (%futex-wait word old to-sec to-usec)))
300 (define-alien-routine "futex_wake"
301 int (word unsigned-long) (n unsigned-long))))
303 ;;; used by debug-int.lisp to access interrupt contexts
304 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
306 (defun sb!vm::current-thread-offset-sap (n)
307 (declare (type (unsigned-byte 27) n))
308 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
309 (* n sb!vm:n-word-bytes)))
312 (defun sb!vm::current-thread-offset-sap (n)
313 (declare (type (unsigned-byte 27) n))
314 (sb!vm::current-thread-offset-sap n))
317 (defmacro with-deadlocks ((thread lock &optional (timeout nil timeoutp)) &body forms)
318 (with-unique-names (n-thread n-lock new n-timeout)
319 `(let* ((,n-thread ,thread)
321 (,n-timeout ,(when timeoutp
323 (when sb!impl::*deadline*
324 sb!impl::*deadline-seconds*))))
326 ;; Using CONS tells the rest of the system there's a
327 ;; timeout in place, so it isn't considered a deadlock.
328 (cons ,n-timeout ,n-lock)
330 (declare (dynamic-extent ,new))
331 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
332 ;; in places where interrupts should already be disabled.
335 (setf (thread-waiting-for ,n-thread) ,new)
338 ;; Interrupt handlers and GC save and restore any
339 ;; previous wait marks using WITHOUT-DEADLOCKS below.
340 (setf (thread-waiting-for ,n-thread) nil)
341 (barrier (:write))))))
346 (setf (fdocumentation 'make-mutex 'function)
348 (fdocumentation 'mutex-name 'function)
349 "The name of the mutex. Setfable.")
351 #!+(and sb-thread sb-futex)
353 (define-structure-slot-addressor mutex-state-address
356 ;; Important: current code assumes these are fixnums or other
357 ;; lisp objects that don't need pinning.
358 (defconstant +lock-free+ 0)
359 (defconstant +lock-taken+ 1)
360 (defconstant +lock-contested+ 2))
362 (defun mutex-owner (mutex)
363 "Current owner of the mutex, NIL if the mutex is free. Naturally,
364 this is racy by design (another thread may acquire the mutex after
365 this function returns), it is intended for informative purposes. For
366 testing whether the current thread is holding a mutex see
368 ;; Make sure to get the current value.
369 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
371 (sb!ext:defglobal **deadlock-lock** nil)
373 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
374 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
375 (defun check-deadlock ()
376 (let* ((self *current-thread*)
379 (thread-waiting-for self))))
380 (labels ((detect-deadlock (lock)
381 (let ((other-thread (mutex-%owner lock)))
382 (cond ((not other-thread))
383 ((eq self other-thread)
385 (with-cas-lock ((symbol-value '**deadlock-lock**))
386 (prog1 (deadlock-chain self origin)
387 ;; We're now committed to signaling the
388 ;; error and breaking the deadlock, so
389 ;; mark us as no longer waiting on the
390 ;; lock. This ensures that a single
391 ;; deadlock is reported in only one
392 ;; thread, and that we don't look like
393 ;; we're waiting on the lock when print
394 ;; stuff -- because that may lead to
395 ;; further deadlock checking, in turn
396 ;; possibly leading to a bogus vicious
397 ;; metacycle on PRINT-OBJECT.
398 (setf (thread-waiting-for self) nil)))))
399 (error 'thread-deadlock
400 :thread *current-thread*
403 (let ((other-lock (progn
405 (thread-waiting-for other-thread))))
406 ;; If the thread is waiting with a timeout OTHER-LOCK
407 ;; is a cons, and we don't consider it a deadlock -- since
408 ;; it will time out on its own sooner or later.
409 (when (mutex-p other-lock)
410 (detect-deadlock other-lock)))))))
411 (deadlock-chain (thread lock)
412 (let* ((other-thread (mutex-owner lock))
413 (other-lock (when other-thread
415 (thread-waiting-for other-thread))))
416 (cond ((not other-thread)
417 ;; The deadlock is gone -- maybe someone unwound
418 ;; from the same deadlock already?
419 (return-from check-deadlock nil))
421 ;; There's a timeout -- no deadlock.
422 (return-from check-deadlock nil))
423 ((waitqueue-p other-lock)
425 (return-from check-deadlock nil))
426 ((eq self other-thread)
428 (list (list thread lock)))
431 (cons (cons thread lock)
432 (deadlock-chain other-thread other-lock))
433 ;; Again, the deadlock is gone?
434 (return-from check-deadlock nil)))))))
435 ;; Timeout means there is no deadlock
436 (when (mutex-p origin)
437 (detect-deadlock origin)
440 (defun %try-mutex (mutex new-owner)
441 (declare (type mutex mutex) (optimize (speed 3)))
443 (let ((old (mutex-%owner mutex)))
444 (when (eq new-owner old)
445 (error "Recursive lock attempt ~S." mutex))
448 (error "Strange deadlock on ~S in an unithreaded build?" mutex))
449 #!-(and sb-thread sb-futex)
451 ;; Don't even bother to try to CAS if it looks bad.
452 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
453 #!+(and sb-thread sb-futex)
454 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
455 (when (eql +lock-free+ (sb!ext:compare-and-swap (mutex-state mutex)
458 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
460 (bug "Old owner in free mutex: ~S" prev))
464 (defun %%wait-for-mutex (mutex new-owner to-sec to-usec stop-sec stop-usec)
465 (declare (type mutex mutex) (optimize (speed 3)))
467 (declare (ignore to-sec to-usec))
473 (not (mutex-%owner mutex)))
474 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil
476 do (return-from cas t)
479 (sb!ext:spin-loop-hint))
480 ;; Check for pending interrupts.
481 (with-interrupts nil)))
482 (declare (dynamic-extent #'cas))
483 (sb!impl::%%wait-for #'cas stop-sec stop-usec))
485 ;; This is a fairly direct translation of the Mutex 2 algorithm from
486 ;; "Futexes are Tricky" by Ulrich Drepper.
488 (when (eql +lock-free+ old)
489 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
492 (bug "Old owner in free mutex: ~S" prev))
493 (return-from %%wait-for-mutex t)))))
494 (prog ((old (sb!ext:compare-and-swap (mutex-state mutex)
495 +lock-free+ +lock-taken+)))
496 ;; Got it right off the bat?
499 ;; Mark it as contested, and sleep. (Exception: it was just released.)
500 (when (or (eql +lock-contested+ old)
501 (not (eql +lock-free+
502 (sb!ext:compare-and-swap
503 (mutex-state mutex) +lock-taken+ +lock-contested+))))
504 (when (eql 1 (with-pinned-objects (mutex)
505 (futex-wait (mutex-state-address mutex)
506 (get-lisp-obj-address +lock-contested+)
509 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
511 ;; 1 = ETIMEDOUT ***DONE***
512 ;; 2 = EINTR, a spurious wakeup
513 (return-from %%wait-for-mutex nil)))
514 ;; Try to get it, still marking it as contested.
516 (sb!ext:compare-and-swap (mutex-state mutex) +lock-free+ +lock-contested+))
517 ;; Update timeout if necessary.
519 (setf (values to-sec to-usec)
520 (sb!impl::relative-decoded-times stop-sec stop-usec)))
525 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
526 (with-deadlocks (self mutex timeout)
527 (with-interrupts (check-deadlock))
530 (return-from %wait-for-mutex
531 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
534 ;; FIXME: substract elapsed time from timeout...
535 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
536 (decode-timeout timeout))
539 (defun get-mutex (mutex &optional new-owner (waitp t) (timeout nil))
541 "Deprecated in favor of GRAB-MUTEX."
542 (declare (ignorable waitp timeout))
543 (let ((new-owner (or new-owner *current-thread*)))
544 (or (%try-mutex mutex new-owner)
547 (multiple-value-call #'%wait-for-mutex
548 mutex new-owner timeout (decode-timeout timeout))))))
550 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
552 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
553 the mutex is not immediately available, sleep until it is available.
555 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
556 GRAB-MUTEX should try to acquire the lock in the contested case.
558 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
559 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
560 that GRAB-MUTEX did -not- acquire the lock.
564 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
568 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
571 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
572 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
573 allows the call to be interrupted from sleep.
575 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
576 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
577 DEADLINE-TIMEOUT if the global deadline was due already on entering
580 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
583 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
586 (declare (ignorable waitp timeout))
587 (let ((self *current-thread*))
588 (or (%try-mutex mutex self)
591 (multiple-value-call #'%wait-for-mutex
592 mutex self timeout (decode-timeout timeout))))))
594 (defun release-mutex (mutex &key (if-not-owner :punt))
596 "Release MUTEX by setting it to NIL. Wake up threads waiting for
599 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
602 If the current thread is not the owner of the mutex then it silently
603 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
604 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
605 IF-NOT-OWNER is :FORCE)."
606 (declare (type mutex mutex))
607 ;; Order matters: set owner to NIL before releasing state.
608 (let* ((self *current-thread*)
609 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
610 (unless (eq self old-owner)
612 ((:punt) (return-from release-mutex nil))
614 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
616 (setf (mutex-%owner mutex) nil)
617 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
620 #!+(and sb-thread sb-futex)
622 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
623 ;; unsigned-byte type this can be used:
625 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
626 ;; (unless (eql old +lock-free+)
627 ;; (setf (mutex-state mutex) +lock-free+)
628 ;; (with-pinned-objects (mutex)
629 ;; (futex-wake (mutex-state-address mutex) 1))))
630 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
631 +lock-taken+ +lock-free+)))
632 (when (eql old +lock-contested+)
633 (sb!ext:compare-and-swap (mutex-state mutex)
634 +lock-contested+ +lock-free+)
635 (with-pinned-objects (mutex)
636 (futex-wake (mutex-state-address mutex) 1))))
640 ;;;; Waitqueues/condition variables
642 #!+(or (not sb-thread) sb-futex)
643 (defstruct (waitqueue (:constructor %make-waitqueue))
646 (name nil :type (or null thread-name))
647 #!+(and sb-thread sb-futex)
650 #!+(and sb-thread (not sb-futex))
652 (defstruct (waitqueue (:constructor %make-waitqueue))
655 (name nil :type (or null thread-name))
656 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
657 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
658 ;; lock. In most cases this should be uncontested thanks to the mutex --
659 ;; the only case where that might not be true is when CONDITION-WAIT
660 ;; unwinds and %WAITQUEUE-DROP is called.
665 (defun %waitqueue-enqueue (thread queue)
666 (setf (thread-waiting-for thread) queue)
667 (let ((head (waitqueue-%head queue))
668 (tail (waitqueue-%tail queue))
671 (setf (waitqueue-%head queue) new))
673 (setf (cdr tail) new))
674 (setf (waitqueue-%tail queue) new)
676 (defun %waitqueue-drop (thread queue)
677 (setf (thread-waiting-for thread) nil)
678 (let ((head (waitqueue-%head queue)))
679 (do ((list head (cdr list))
682 (eq (car list) thread))
684 (let ((rest (cdr list)))
686 (setf (cdr prev) rest))
688 (setf (waitqueue-%head queue) rest
691 (setf (waitqueue-%tail queue) prev)))))))
693 (defun %waitqueue-wakeup (queue n)
695 (loop while (plusp n)
696 for next = (let ((head (waitqueue-%head queue))
697 (tail (waitqueue-%tail queue)))
700 (setf (waitqueue-%head queue) nil
701 (waitqueue-%tail queue) nil)
702 (setf (waitqueue-%head queue) (cdr head)))
705 do (when (eq queue (sb!ext:compare-and-swap
706 (thread-waiting-for next) queue nil))
710 (def!method print-object ((waitqueue waitqueue) stream)
711 (print-unreadable-object (waitqueue stream :type t :identity t)
712 (format stream "~@[~A~]" (waitqueue-name waitqueue))))
714 (defun make-waitqueue (&key name)
716 "Create a waitqueue."
717 (%make-waitqueue :name name))
720 (setf (fdocumentation 'waitqueue-name 'function)
721 "The name of the waitqueue. Setfable.")
723 #!+(and sb-thread sb-futex)
724 (define-structure-slot-addressor waitqueue-token-address
728 (defun condition-wait (queue mutex &key timeout)
730 "Atomically release MUTEX and start waiting on QUEUE for till another thread
731 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
732 queue, at which point we re-acquire MUTEX and return T.
734 Spurious wakeups are possible.
736 If TIMEOUT is given, it is the maximum number of seconds to wait, including
737 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
738 wakeup and re-acquisition do not occur within the given time, returns NIL
739 without re-acquiring the mutex.
741 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
743 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
744 occurred the correct way to write code that uses CONDITION-WAIT is to loop
745 around the call, checking the the associated data:
748 (defvar *queue* (make-waitqueue))
749 (defvar *lock* (make-mutex))
752 (defun pop-data (&optional timeout)
755 do (or (condition-wait *queue* *lock* :timeout timeout)
756 ;; Lock not held, must unwind without touching *data*.
757 (return-from pop-data nil)))
761 (defun push-data (data)
764 (condition-notify *queue*)))
767 (declare (ignore queue))
770 (sb!ext:wait-for nil :timeout timeout) ; Yeah...
772 (let ((me *current-thread*))
774 (assert (eq me (mutex-%owner mutex)))
775 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
776 (decode-timeout timeout)
777 (let ((status :interrupted))
778 ;; Need to disable interrupts so that we don't miss grabbing the
779 ;; mutex on our way out.
785 (%with-cas-lock ((waitqueue-%owner queue))
786 (%waitqueue-enqueue me queue))
787 (release-mutex mutex)
789 (or (flet ((wakeup ()
791 (unless (eq queue (thread-waiting-for me))
793 (declare (dynamic-extent #'wakeup))
794 (allow-with-interrupts
795 (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
798 (with-pinned-objects (queue me)
799 (setf (waitqueue-token queue) me)
800 (release-mutex mutex)
801 ;; Now we go to sleep using futex-wait. If anyone else
802 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
803 ;; this comment, it will change the token, and so futex-wait
804 ;; returns immediately instead of sleeping. Ergo, no lost
805 ;; wakeup. We may get spurious wakeups, but that's ok.
807 (case (allow-with-interrupts
808 (futex-wait (waitqueue-token-address queue)
809 (get-lisp-obj-address me)
810 ;; our way of saying "no
818 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
820 ;; 2 = EINTR, a spurious wakeup
823 (%with-cas-lock ((waitqueue-%owner queue))
824 (if (eq queue (thread-waiting-for me))
825 (%waitqueue-drop me queue)
826 (unless (eq :ok status)
827 ;; CONDITION-NOTIFY thinks we've been woken up, but really
828 ;; we're unwinding. Wake someone else up.
829 (%waitqueue-wakeup queue 1))))
830 ;; Update timeout for mutex re-aquisition.
831 (when (and (eq :ok status) to-sec)
832 (setf (values to-sec to-usec)
833 (sb!impl::relative-decoded-times stop-sec stop-usec)))
834 ;; If we ran into deadline, try to get the mutex before
835 ;; signaling. If we don't unwind it will look like a normal
836 ;; return from user perspective.
837 (when (and (eq :timeout status) deadlinep)
838 (let ((got-it (%try-mutex mutex me)))
839 (allow-with-interrupts
842 (return-from condition-wait t))
844 ;; The deadline may have changed.
845 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
846 (decode-timeout timeout))
847 (setf status :ok))))))
848 ;; Re-acquire the mutex for normal return.
849 (when (eq :ok status)
850 (unless (or (%try-mutex mutex me)
851 (allow-with-interrupts
852 (%wait-for-mutex mutex me timeout
854 stop-sec stop-usec deadlinep)))
855 (setf status :timeout)))))
857 (unless (eq :timeout status)
858 ;; The only case we return normally without re-acquiring the
859 ;; mutex is when there is a :TIMEOUT that runs out.
860 (bug "CONDITION-WAIT: invalid status on normal return: ~S" status)))))))
862 (defun condition-notify (queue &optional (n 1))
864 "Notify N threads waiting on QUEUE.
866 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
867 must be held by this thread during this call."
869 (declare (ignore queue n))
871 (error "Not supported in unithread builds.")
873 (declare (type (and fixnum (integer 1)) n))
874 (/show0 "Entering CONDITION-NOTIFY")
878 (with-cas-lock ((waitqueue-%owner queue))
879 (%waitqueue-wakeup queue n))
882 ;; No problem if >1 thread notifies during the comment in condition-wait:
883 ;; as long as the value in queue-data isn't the waiting thread's id, it
884 ;; matters not what it is -- using the queue object itself is handy.
886 ;; XXX we should do something to ensure that the result of this setf
887 ;; is visible to all CPUs.
889 ;; ^-- surely futex_wake() involves a memory barrier?
890 (setf (waitqueue-token queue) queue)
891 (with-pinned-objects (queue)
892 (futex-wake (waitqueue-token-address queue) n)))))
894 (defun condition-broadcast (queue)
896 "Notify all threads waiting on QUEUE.
898 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
899 must be held by this thread during this call."
900 (condition-notify queue
901 ;; On a 64-bit platform truncating M-P-F to an int
902 ;; results in -1, which wakes up only one thread.
904 most-positive-fixnum)))
909 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
911 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
912 should be considered an implementation detail, and may change in the
914 (name nil :type (or null thread-name))
915 (%count 0 :type (integer 0))
916 (waitcount 0 :type sb!vm:word)
918 (queue (make-waitqueue)))
920 (setf (fdocumentation 'semaphore-name 'function)
921 "The name of the semaphore INSTANCE. Setfable.")
923 (defstruct (semaphore-notification (:constructor make-semaphore-notification ())
926 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
927 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
928 multiple threads are using the same notification object in parallel."
929 (%status nil :type boolean))
931 (setf (fdocumentation 'make-semaphore-notification 'function)
932 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
935 (declaim (inline semaphore-notification-status))
936 (defun semaphore-notification-status (semaphore-notification)
938 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
939 SEMAPHORE-NOTICATION has succeeded since the notification object was created
942 (semaphore-notification-%status semaphore-notification))
944 (declaim (inline clear-semaphore-notification))
945 (defun clear-semaphore-notification (semaphore-notification)
947 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
948 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
950 (setf (semaphore-notification-%status semaphore-notification) nil)))
952 (declaim (inline semaphore-count))
953 (defun semaphore-count (instance)
955 "Returns the current count of the semaphore INSTANCE."
957 (semaphore-%count instance))
959 (defun make-semaphore (&key name (count 0))
961 "Create a semaphore with the supplied COUNT and NAME."
962 (%make-semaphore name count))
964 (defun wait-on-semaphore (semaphore &key timeout notification)
966 "Decrement the count of SEMAPHORE if the count would not be negative. Else
967 blocks until the semaphore can be decremented. Returns T on success.
969 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
970 cannot be decremented in that time, returns NIL without decrementing the
973 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
974 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
975 decrements the count, the status is set to T."
976 (when (and notification (semaphore-notification-status notification))
977 (with-simple-restart (continue "Clear notification status and continue.")
978 (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
979 'wait-on-semaphore semaphore))
980 (clear-semaphore-notification notification))
981 ;; A more direct implementation based directly on futexes should be
984 ;; We need to disable interrupts so that we don't forget to
985 ;; decrement the waitcount (which would happen if an asynch
986 ;; interrupt should catch us on our way out from the loop.)
988 ;; FIXME: No timeout on initial mutex acquisition.
989 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
990 ;; Quick check: is it positive? If not, enter the wait loop.
991 (let ((count (semaphore-%count semaphore)))
993 (setf (semaphore-%count semaphore) (1- count))
995 (setf (semaphore-notification-%status notification) t)))
999 ;; Need to use ATOMIC-INCF despite the lock, because on our
1000 ;; way out from here we might not be locked anymore -- so
1001 ;; another thread might be tweaking this in parallel using
1002 ;; ATOMIC-DECF. No danger over overflow, since there it
1003 ;; at most one increment per thread waiting on the semaphore.
1004 (sb!ext:atomic-incf (semaphore-waitcount semaphore))
1005 (loop until (plusp (setf count (semaphore-%count semaphore)))
1006 do (or (condition-wait (semaphore-queue semaphore)
1007 (semaphore-mutex semaphore)
1009 (return-from wait-on-semaphore nil)))
1010 (setf (semaphore-%count semaphore) (1- count))
1012 (setf (semaphore-notification-%status notification) t)))
1013 ;; Need to use ATOMIC-DECF as we may unwind without the lock
1015 (sb!ext:atomic-decf (semaphore-waitcount semaphore)))))))
1018 (defun try-semaphore (semaphore &optional (n 1) notification)
1020 "Try to decrement the count of SEMAPHORE by N. If the count were to
1021 become negative, punt and return NIL, otherwise return true.
1023 If NOTIFICATION is given it must be a semaphore notification object
1024 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1025 the status is set to T."
1026 (declare (type (integer 1) n))
1027 (when (and notification (semaphore-notification-status notification))
1028 (with-simple-restart (continue "Clear notification status and continue.")
1029 (error "~@<Semaphore notification object status not cleared on entry to ~S on ~S.~:@>"
1030 'try-semaphore semaphore))
1031 (clear-semaphore-notification notification))
1032 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1033 (let ((new-count (- (semaphore-%count semaphore) n)))
1034 (when (not (minusp new-count))
1035 (setf (semaphore-%count semaphore) new-count)
1037 (setf (semaphore-notification-%status notification) t))
1038 ;; FIXME: We don't actually document this -- should we just
1039 ;; return T, or document new count as the return?
1042 (defun signal-semaphore (semaphore &optional (n 1))
1044 "Increment the count of SEMAPHORE by N. If there are threads waiting
1045 on this semaphore, then N of them is woken up."
1046 (declare (type (integer 1) n))
1047 ;; Need to disable interrupts so that we don't lose a wakeup after
1048 ;; we have incremented the count.
1049 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1050 (let ((waitcount (semaphore-waitcount semaphore))
1051 (count (incf (semaphore-%count semaphore) n)))
1052 (when (plusp waitcount)
1053 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1056 ;;;; Job control, independent listeners
1059 (lock (make-mutex :name "session lock"))
1061 (interactive-threads nil)
1062 (interactive-threads-queue (make-waitqueue)))
1064 (defvar *session* nil)
1066 ;;; The debugger itself tries to acquire the session lock, don't let
1067 ;;; funny situations (like getting a sigint while holding the session
1068 ;;; lock) occur. At the same time we need to allow interrupts while
1069 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1070 ;;; be interruptible.
1072 ;;; Take care: we sometimes need to obtain the session lock while
1073 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1074 ;;; _after_ getting a session lock! (Deadlock risk.)
1076 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1078 (defmacro with-session-lock ((session) &body body)
1079 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1082 (defun new-session ()
1083 (make-session :threads (list *current-thread*)
1084 :interactive-threads (list *current-thread*)))
1086 (defun init-job-control ()
1087 (/show0 "Entering INIT-JOB-CONTROL")
1088 (setf *session* (new-session))
1089 (/show0 "Exiting INIT-JOB-CONTROL"))
1091 (defun %delete-thread-from-session (thread session)
1092 (with-session-lock (session)
1093 (setf (session-threads session)
1094 (delete thread (session-threads session))
1095 (session-interactive-threads session)
1096 (delete thread (session-interactive-threads session)))))
1098 (defun call-with-new-session (fn)
1099 (%delete-thread-from-session *current-thread* *session*)
1100 (let ((*session* (new-session)))
1103 (defmacro with-new-session (args &body forms)
1104 (declare (ignore args)) ;for extensibility
1105 (sb!int:with-unique-names (fb-name)
1106 `(labels ((,fb-name () ,@forms))
1107 (call-with-new-session (function ,fb-name)))))
1109 ;;; Remove thread from its session, if it has one.
1111 (defun handle-thread-exit (thread)
1112 (/show0 "HANDLING THREAD EXIT")
1113 ;; Lisp-side cleanup
1114 (with-all-threads-lock
1115 (setf (thread-%alive-p thread) nil)
1116 (setf (thread-os-thread thread) nil)
1117 (setq *all-threads* (delete thread *all-threads*))
1119 (%delete-thread-from-session thread *session*))))
1121 (defun terminate-session ()
1123 "Kill all threads in session except for this one. Does nothing if current
1124 thread is not the foreground thread."
1125 ;; FIXME: threads created in other threads may escape termination
1127 (with-session-lock (*session*)
1128 (and (eq *current-thread*
1129 (car (session-interactive-threads *session*)))
1130 (session-threads *session*)))))
1131 ;; do the kill after dropping the mutex; unwind forms in dying
1132 ;; threads may want to do session things
1133 (dolist (thread to-kill)
1134 (unless (eq thread *current-thread*)
1135 ;; terminate the thread but don't be surprised if it has
1136 ;; exited in the meantime
1137 (handler-case (terminate-thread thread)
1138 (interrupt-thread-error ()))))))
1140 ;;; called from top of invoke-debugger
1141 (defun debugger-wait-until-foreground-thread (stream)
1142 "Returns T if thread had been running in background, NIL if it was
1144 (declare (ignore stream))
1148 (with-session-lock (*session*)
1149 (not (member *current-thread*
1150 (session-interactive-threads *session*))))
1153 (defun get-foreground ()
1156 (let ((was-foreground t))
1158 (/show0 "Looping in GET-FOREGROUND")
1159 (with-session-lock (*session*)
1160 (let ((int-t (session-interactive-threads *session*)))
1161 (when (eq (car int-t) *current-thread*)
1162 (unless was-foreground
1163 (format *query-io* "Resuming thread ~A~%" *current-thread*))
1164 (return-from get-foreground t))
1165 (setf was-foreground nil)
1166 (unless (member *current-thread* int-t)
1167 (setf (cdr (last int-t))
1168 (list *current-thread*)))
1170 (session-interactive-threads-queue *session*)
1171 (session-lock *session*)))))))
1173 (defun release-foreground (&optional next)
1175 "Background this thread. If NEXT is supplied, arrange for it to
1176 have the foreground next."
1177 #!-sb-thread (declare (ignore next))
1180 (with-session-lock (*session*)
1181 (when (rest (session-interactive-threads *session*))
1182 (setf (session-interactive-threads *session*)
1183 (delete *current-thread* (session-interactive-threads *session*))))
1185 (setf (session-interactive-threads *session*)
1187 (delete next (session-interactive-threads *session*)))))
1188 (condition-broadcast (session-interactive-threads-queue *session*))))
1190 (defun foreground-thread ()
1191 (car (session-interactive-threads *session*)))
1193 (defun make-listener-thread (tty-name)
1194 (assert (probe-file tty-name))
1195 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1196 (out (sb!unix:unix-dup in))
1197 (err (sb!unix:unix-dup in)))
1198 (labels ((thread-repl ()
1199 (sb!unix::unix-setsid)
1200 (let* ((sb!impl::*stdin*
1201 (make-fd-stream in :input t :buffering :line
1204 (make-fd-stream out :output t :buffering :line
1207 (make-fd-stream err :output t :buffering :line
1210 (make-fd-stream err :input t :output t
1213 (sb!impl::*descriptor-handlers* nil))
1214 (with-new-session ()
1216 (sb!impl::toplevel-repl nil)
1217 (sb!int:flush-standard-output-streams))))))
1218 (make-thread #'thread-repl))))
1223 (defun make-thread (function &key name arguments)
1225 "Create a new thread of NAME that runs FUNCTION with the argument
1226 list designator provided (defaults to no argument). When the function
1227 returns the thread exits. The return values of FUNCTION are kept
1228 around and can be retrieved by JOIN-THREAD."
1229 #!-sb-thread (declare (ignore function name arguments))
1230 #!-sb-thread (error "Not supported in unithread builds.")
1231 #!+sb-thread (assert (or (atom arguments)
1232 (null (cdr (last arguments))))
1234 "Argument passed to ~S, ~S, is an improper list."
1235 'make-thread arguments)
1237 (let* ((thread (%make-thread :name name))
1238 (setup-sem (make-semaphore :name "Thread setup semaphore"))
1239 (real-function (coerce function 'function))
1240 (arguments (if (listp arguments)
1244 (named-lambda initial-thread-function ()
1245 ;; In time we'll move some of the binding presently done in C
1248 ;; KLUDGE: Here we have a magic list of variables that are
1249 ;; not thread-safe for one reason or another. As people
1250 ;; report problems with the thread safety of certain
1251 ;; variables, (e.g. "*print-case* in multiple threads
1252 ;; broken", sbcl-devel 2006-07-14), we add a few more
1253 ;; bindings here. The Right Thing is probably some variant
1254 ;; of Allegro's *cl-default-special-bindings*, as that is at
1255 ;; least accessible to users to secure their own libraries.
1256 ;; --njf, 2006-07-15
1258 ;; As it is, this lambda must not cons until we are ready
1259 ;; to run GC. Be very careful.
1260 (let* ((*current-thread* thread)
1261 (*restart-clusters* nil)
1262 (*handler-clusters* (sb!kernel::initial-handler-clusters))
1263 (*condition-restarts* nil)
1264 (sb!impl::*deadline* nil)
1265 (sb!impl::*deadline-seconds* nil)
1266 (sb!impl::*step-out* nil)
1267 ;; internal printer variables
1268 (sb!impl::*previous-case* nil)
1269 (sb!impl::*previous-readtable-case* nil)
1270 (sb!impl::*internal-symbol-output-fun* nil)
1271 (sb!impl::*descriptor-handlers* nil)) ; serve-event
1273 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1274 (setf (thread-os-thread thread) (current-thread-os-thread))
1275 (with-mutex ((thread-result-lock thread))
1276 (with-all-threads-lock
1277 (push thread *all-threads*))
1278 (with-session-lock (*session*)
1279 (push thread (session-threads *session*)))
1280 (setf (thread-%alive-p thread) t)
1281 (signal-semaphore setup-sem)
1282 ;; can't use handling-end-of-the-world, because that flushes
1283 ;; output streams, and we don't necessarily have any (or we
1284 ;; could be sharing them)
1285 (catch 'sb!impl::toplevel-catcher
1286 (catch 'sb!impl::%end-of-the-world
1287 (with-simple-restart
1290 "~~@<Terminate this thread (~A)~~@:>"
1294 (with-local-interrupts
1295 ;; Now that most things have a chance
1296 ;; to work properly without messing up
1297 ;; other threads, it's time to enable
1299 (sb!unix::unblock-deferrable-signals)
1300 (setf (thread-result thread)
1302 (multiple-value-list
1303 (apply real-function arguments))))
1304 ;; Try to block deferrables. An
1305 ;; interrupt may unwind it, but for a
1306 ;; normal exit it prevents interrupt
1308 (block-deferrable-signals))
1309 ;; We're going down, can't handle interrupts
1310 ;; sanely anymore. GC remains enabled.
1311 (block-deferrable-signals)
1312 ;; We don't want to run interrupts in a dead
1313 ;; thread when we leave WITHOUT-INTERRUPTS.
1314 ;; This potentially causes important
1315 ;; interupts to be lost: SIGINT comes to
1317 (setq *interrupt-pending* nil)
1318 (handle-thread-exit thread))))))))
1320 ;; If the starting thread is stopped for gc before it signals the
1321 ;; semaphore then we'd be stuck.
1322 (assert (not *gc-inhibit*))
1323 ;; Keep INITIAL-FUNCTION pinned until the child thread is
1324 ;; initialized properly. Wrap the whole thing in
1325 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
1328 (with-pinned-objects (initial-function)
1331 (get-lisp-obj-address initial-function))))
1332 (when (zerop os-thread)
1333 (error "Can't create a new thread"))
1334 (wait-on-semaphore setup-sem)
1337 (defun join-thread (thread &key (default nil defaultp) timeout)
1339 "Suspend current thread until THREAD exits. Return the result values of the
1342 If the thread does not exit normally within TIMEOUT seconds return DEFAULT if
1343 given, or else signal JOIN-THREAD-ERROR.
1345 NOTE: Return convention in case of a timeout is exprimental and subject to
1347 (let ((lock (thread-result-lock thread))
1353 (allow-with-interrupts
1354 ;; Don't use the timeout if the thread is not alive anymore.
1355 (grab-mutex lock :timeout (and (thread-alive-p thread) timeout))))
1356 (cond ((car (thread-result thread))
1357 (return-from join-thread
1358 (values-list (cdr (thread-result thread)))))
1360 (return-from join-thread default))
1362 (setf problem :abort)))
1364 (return-from join-thread default)))
1366 (release-mutex lock))))
1367 (error 'join-thread-error :thread thread :problem problem)))
1369 (defun destroy-thread (thread)
1371 "Deprecated. Same as TERMINATE-THREAD."
1372 (terminate-thread thread))
1374 (defmacro with-interruptions-lock ((thread) &body body)
1375 `(with-system-mutex ((thread-interruptions-lock ,thread))
1378 ;;; Called from the signal handler.
1380 (defun run-interruption ()
1381 (let ((interruption (with-interruptions-lock (*current-thread*)
1382 (pop (thread-interruptions *current-thread*)))))
1383 ;; If there is more to do, then resignal and let the normal
1384 ;; interrupt deferral mechanism take care of the rest. From the
1385 ;; OS's point of view the signal we are in the handler for is no
1386 ;; longer pending, so the signal will not be lost.
1387 (when (thread-interruptions *current-thread*)
1388 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1390 (funcall interruption))))
1392 (defun interrupt-thread (thread function)
1394 "Interrupt THREAD and make it run FUNCTION.
1396 The interrupt is asynchronous, and can occur anywhere with the exception of
1397 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1399 FUNCTION is called with interrupts disabled, under
1400 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1401 enable interrupts internally, in most cases FUNCTION should either enter
1402 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1403 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1405 When a thread receives multiple interrupts, they are executed in the order
1406 they were sent -- first in, first out.
1408 This means that a great degree of care is required to use INTERRUPT-THREAD
1409 safely and sanely in a production environment. The general recommendation is
1410 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1411 entirely from production environments -- it is simply exceedingly hard to use
1414 With those caveats in mind, what you need to know when using it:
1416 * If calling FUNCTION causes a non-local transfer of control (ie. an
1417 unwind), all normal cleanup forms will be executed.
1419 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1420 it is just as if that had happened due to a regular GO, THROW, or
1421 RETURN-FROM: the interrupted cleanup form and those following it in the
1422 same UNWIND-PROTECT do not get executed.
1424 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1425 frankly an unreasonable expectation for third party libraries, especially
1426 given that asynch-unwind-safety does not compose: a function calling
1427 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1429 This means that in order for an asych unwind to be safe, the entire
1430 callstack at the point of interruption needs to be asynch-unwind-safe.
1432 * In addition to asynch-unwind-safety you must consider the issue of
1433 re-entrancy. INTERRUPT-THREAD can cause function that are never normally
1434 called recursively to be re-entered during their dynamic contour,
1435 which may cause them to misbehave. (Consider binding of special variables,
1436 values of global variables, etc.)
1438 Take togather, these two restrict the \"safe\" things to do using
1439 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1440 interactive development use is using it to force entry to debugger to inspect
1441 the state of a thread:
1443 (interrupt-thread thread #'break)
1445 Short version: be careful out there."
1447 (declare (ignore thread))
1449 (with-interrupt-bindings
1450 (with-interrupts (funcall function)))
1452 (let ((os-thread (thread-os-thread thread)))
1453 (cond ((not os-thread)
1454 (error 'interrupt-thread-error :thread thread))
1456 (with-interruptions-lock (thread)
1457 ;; Append to the end of the interruptions queue. It's
1458 ;; O(N), but it does not hurt to slow interruptors down a
1459 ;; bit when the queue gets long.
1460 (setf (thread-interruptions thread)
1461 (append (thread-interruptions thread)
1464 (allow-with-interrupts
1465 (funcall function))))))))
1466 (when (minusp (kill-safely os-thread sb!unix:sigpipe))
1467 (error 'interrupt-thread-error :thread thread))))))
1469 (defun terminate-thread (thread)
1471 "Terminate the thread identified by THREAD, by interrupting it and causing
1472 it to call SB-EXT:QUIT.
1474 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that eg. thread
1480 (setf foo (get-foo))
1483 ;; An interrupt occurring inside the cleanup clause
1484 ;; will cause cleanups from the current UNWIND-PROTECT
1486 (release-foo foo))))
1488 might miss calling RELEASE-FOO despite GET-FOO having returned true if the
1489 interrupt occurs inside the cleanup clause, eg. during execution of
1492 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need to use
1496 (sb-sys:without-interrupts
1499 (setf foo (sb-sys:allow-with-interrupts
1501 (sb-sys:with-local-interrupts
1504 (release-foo foo)))))
1506 Since most libraries using UNWIND-PROTECT do not do this, you should never
1507 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1508 (interrupt-thread thread 'sb!ext:quit))
1510 (define-alien-routine "thread_yield" int)
1513 (setf (fdocumentation 'thread-yield 'function)
1514 "Yield the processor to other threads.")
1516 ;;; internal use only. If you think you need to use these, either you
1517 ;;; are an SBCL developer, are doing something that you should discuss
1518 ;;; with an SBCL developer first, or are doing something that you
1519 ;;; should probably discuss with a professional psychiatrist first
1522 (defun %thread-sap (thread)
1523 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1524 (target (thread-os-thread thread)))
1526 (when (sap= thread-sap (int-sap 0)) (return nil))
1527 (let ((os-thread (sap-ref-word thread-sap
1528 (* sb!vm:n-word-bytes
1529 sb!vm::thread-os-thread-slot))))
1530 (when (= os-thread target) (return thread-sap))
1532 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1533 sb!vm::thread-next-slot)))))))
1535 (defun %symbol-value-in-thread (symbol thread)
1536 ;; Prevent the thread from dying completely while we look for the TLS
1538 (with-all-threads-lock
1540 (if (thread-alive-p thread)
1541 (let* ((offset (sb!kernel:get-lisp-obj-address
1542 (sb!vm::symbol-tls-index symbol)))
1543 (obj (sap-ref-lispobj (%thread-sap thread) offset))
1544 (tl-val (sb!kernel:get-lisp-obj-address obj)))
1545 (cond ((zerop offset)
1546 (return (values nil :no-tls-value)))
1547 ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1548 (eql tl-val sb!vm:unbound-marker-widetag))
1549 (return (values nil :unbound-in-thread)))
1551 (return (values obj :ok)))))
1552 (return (values nil :thread-dead))))))
1554 (defun %set-symbol-value-in-thread (symbol thread value)
1555 (with-pinned-objects (value)
1556 ;; Prevent the thread from dying completely while we look for the TLS
1558 (with-all-threads-lock
1559 (if (thread-alive-p thread)
1560 (let ((offset (sb!kernel:get-lisp-obj-address
1561 (sb!vm::symbol-tls-index symbol))))
1562 (cond ((zerop offset)
1563 (values nil :no-tls-value))
1565 (setf (sap-ref-lispobj (%thread-sap thread) offset)
1567 (values value :ok))))
1568 (values nil :thread-dead)))))
1570 (define-alien-variable tls-index-start unsigned-int)
1572 ;; Get values from the TLS area of the current thread.
1573 (defun %thread-local-references ()
1575 (let ((sap (%thread-sap *current-thread*)))
1576 (loop for index from tls-index-start
1577 below (symbol-value 'sb!vm::*free-tls-index*)
1578 for value = (sap-ref-word sap (* sb!vm:n-word-bytes index))
1579 for (obj ok) = (multiple-value-list (sb!kernel:make-lisp-obj value nil))
1581 (typep obj '(or fixnum character))
1583 '(#.sb!vm:no-tls-value-marker-widetag
1584 #.sb!vm:unbound-marker-widetag))
1585 (member obj seen :test #'eq))
1586 collect obj into seen
1587 finally (return seen))))))
1589 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1590 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1593 If the value cannot be retrieved (because the thread has exited or because it
1594 has no local binding for NAME) and ERRORP is true signals an error of type
1595 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1596 NIL, and a secondary value of NIL.
1598 Can also be used with SETF to change the thread-local value of SYMBOL.
1600 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1601 mechanism for inter-thread communication."
1602 (declare (symbol symbol) (thread thread))
1604 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1608 (error 'symbol-value-in-thread-error
1611 :info (list :read status))
1615 (values (symbol-value symbol) t)
1617 (error 'symbol-value-in-thread-error
1620 :info (list :read :unbound-in-thread))
1623 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1624 (declare (symbol symbol) (thread thread))
1626 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1630 (error 'symbol-value-in-thread-error
1633 :info (list :write status))
1637 (values (setf (symbol-value symbol) value) t)
1639 (error 'symbol-value-in-thread-error
1642 :info (list :write :unbound-in-thread))
1645 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1646 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1651 (defun thread-stepping ()
1653 (sap-ref-word (current-thread-sap)
1654 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1656 (defun (setf thread-stepping) (value)
1657 (setf (sap-ref-word (current-thread-sap)
1658 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1659 (get-lisp-obj-address value)))