WAIT-ON-SEMAPHORE could block indefinitely despite :TIMEOUT being supplied
[sbcl.git] / src / code / target-thread.lisp
blob52be3c5cbff92b910f46d7a93e6ef5a4948f55ac
1 ;;;; support for threads in the target machine
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
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")
14 ;;; CAS Lock
15 ;;;
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
19 ;;; builds.
21 (defmacro with-cas-lock ((place) &body body)
22 #!+sb-doc
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
31 long.
33 WITH-CAS-LOCK can be entered recursively."
34 `(without-interrupts
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)
42 (,owner (progn
43 (barrier (:read))
44 ,read-form))
45 (,self *current-thread*)
46 (,old nil)
47 (,new ,self))
48 (unwind-protect
49 (progn
50 (unless (eq ,owner ,self)
51 (loop until (loop repeat 100
52 when (and (progn
53 (barrier (:read))
54 (not ,read-form))
55 (not (setf ,owner ,cas-form)))
56 return t
57 else
58 do (sb!ext:spin-loop-hint))
59 do (thread-yield)))
60 ,@body)
61 (unless (eq ,owner ,self)
62 (let ((,old ,self)
63 (,new nil))
64 (unless (eq ,old ,cas-form)
65 (bug "Failed to release CAS lock!")))))))))
67 ;;; Conditions
69 (define-condition thread-error (error)
70 ((thread :reader thread-error-thread :initarg :thread))
71 #!+sb-doc
72 (:documentation
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)
78 ())
80 (define-condition thread-deadlock (thread-error)
81 ((cycle :initarg :cycle :reader thread-deadlock-cycle))
82 (:report
83 (lambda (condition stream)
84 (let* ((*print-circle* t)
85 (cycle (thread-deadlock-cycle condition))
86 (start (caar cycle)))
87 (format stream "Deadlock cycle detected:~%")
88 (loop for part = (pop cycle)
89 while part
90 do (format stream " ~S~% waited for:~% ~S~% owned by:~%"
91 (car part)
92 (cdr part)))
93 (format stream " ~S~%" start)))))
95 #!+sb-doc
96 (setf
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))
102 (:report
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)
110 (ecase problem
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."))))))
115 #!+sb-doc
116 (:documentation
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)
126 (:abort
127 (format s "Joining thread failed: thread ~A ~
128 did not return normally."
129 (thread-error-thread c)))
130 (:timeout
131 (format s "Joining thread timed out: thread ~A ~
132 did not exit in time."
133 (thread-error-thread c))))))
134 #!+sb-doc
135 (:documentation
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
141 (condition)
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))))
148 #!+sb-doc
149 (:documentation
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
154 (condition)
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
163 ;;; available, yet
164 #!+sb-doc
165 (setf (fdocumentation '*current-thread* 'variable)
166 "Bound in each thread to the thread itself.")
168 #!+sb-doc
169 (setf
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)
178 :running
179 (multiple-value-list
180 (join-thread thread :default cookie))))
181 (state (if (eq :running info)
182 (let* ((thing (progn
183 (barrier (:read))
184 (thread-waiting-for thread))))
185 (typecase thing
186 (cons
187 (list "waiting on:" (cdr thing)
188 "timeout: " (car thing)))
189 (null
190 (list info))
192 (list "waiting on:" thing))))
193 (if (eq cookie (car info))
194 (list :aborted)
195 :finished)))
196 (values (when (eq :finished state)
197 info))
198 (*print-level* 4))
199 (format stream
200 "~@[~S ~]~:[~{~I~A~^~2I~_ ~}~_~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
201 (thread-name thread)
202 (eq :finished state)
203 state
204 values))))
206 (defun print-lock (lock name owner stream)
207 (let ((*print-circle* t))
208 (print-unreadable-object (lock stream :type t :identity (not name))
209 (if owner
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)
217 #!+sb-doc
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
220 any time."
221 (thread-%alive-p thread))
223 (defun thread-ephemeral-p (thread)
224 #!+sb-doc
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*)
241 ,@body))
243 (defun list-all-threads ()
244 #!+sb-doc
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 ()
257 #!+sb-thread
258 (sap-int (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot))
259 #!-sb-thread
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"
270 :%alive-p t)))
271 (setf (thread-os-thread initial-thread) (current-thread-os-thread)
272 *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 #!+sb-doc
282 "Returns the main thread of the process."
283 *initial-thread*)
285 (defun main-thread-p (&optional (thread *current-thread*))
286 #!+sb-doc
287 "True if THREAD, defaulting to current thread, is the main thread of the process."
288 (eq thread *initial-thread*))
290 (defmacro return-from-thread (values-form &key allow-exit)
291 #!+sb-doc
292 "Unwinds from and terminates the current thread, with values from
293 VALUES-FORM as the results visible to JOIN-THREAD.
295 If current thread is the main thread of the process (see
296 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
297 terminating the main thread would terminate the entire process. If
298 ALLOW-EXIT is true, returning from the main thread is equivalent to
299 calling SB-EXT:EXIT with :CODE 0 and :ABORT NIL.
301 See also: ABORT-THREAD and SB-EXT:EXIT."
302 `(%return-from-thread (multiple-value-list ,values-form) ,allow-exit))
304 (defun %return-from-thread (values allow-exit)
305 (let ((self *current-thread*))
306 (cond ((main-thread-p self)
307 (unless allow-exit
308 (error 'simple-thread-error
309 :format-control "~@<Tried to return ~S as values from main thread, ~
310 but exit was not allowed.~:@>"
311 :format-arguments (list values)
312 :thread self))
313 (sb!ext:exit :code 0))
315 (throw '%return-from-thread (values-list values))))))
317 (defun abort-thread (&key allow-exit)
318 #!+sb-doc
319 "Unwinds from and terminates the current thread abnormally, causing
320 JOIN-THREAD on current thread to signal an error unless a
321 default-value is provided.
323 If current thread is the main thread of the process (see
324 MAIN-THREAD-P), signals an error unless ALLOW-EXIT is true, as
325 terminating the main thread would terminate the entire process. If
326 ALLOW-EXIT is true, aborting the main thread is equivalent to calling
327 SB-EXT:EXIT code 1 and :ABORT NIL.
329 Invoking the initial ABORT restart established by MAKE-THREAD is
330 equivalent to calling ABORT-THREAD in other than main threads.
331 However, whereas ABORT restart may be rebound, ABORT-THREAD always
332 unwinds the entire thread. (Behaviour of the initial ABORT restart for
333 main thread depends on the :TOPLEVEL argument to
334 SB-EXT:SAVE-LISP-AND-DIE.)
336 See also: RETURN-FROM-THREAD and SB-EXT:EXIT."
337 (let ((self *current-thread*))
338 (cond ((main-thread-p self)
339 (unless allow-exit
340 (error 'simple-thread-error
341 :format-control "~@<Tried to abort initial thread, but ~
342 exit was not allowed.~:@>"))
343 (sb!ext:exit :code 1))
345 ;; We /could/ use TOPLEVEL-CATCHER or %END-OF-THE-WORLD as well, but
346 ;; this seems tidier. Those to are a bit too overloaded already.
347 (throw '%abort-thread t)))))
350 ;;;; Aliens, low level stuff
352 (define-alien-routine "kill_safely"
353 integer
354 (os-thread #!-alpha unsigned #!+alpha unsigned-int)
355 (signal int))
357 (define-alien-routine "wake_thread"
358 integer
359 (os-thread unsigned))
361 #!+sb-thread
362 (progn
363 ;; FIXME it would be good to define what a thread id is or isn't
364 ;; (our current assumption is that it's a fixnum). It so happens
365 ;; that on Linux it's a pid, but it might not be on posix thread
366 ;; implementations.
367 (define-alien-routine ("create_thread" %create-thread)
368 unsigned (lisp-fun-address unsigned))
370 (declaim (inline %block-deferrable-signals))
371 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals)
372 void
373 (where unsigned)
374 (old unsigned))
376 (defun block-deferrable-signals ()
377 (%block-deferrable-signals 0 0))
379 #!+sb-futex
380 (progn
381 (declaim (inline futex-wait %futex-wait futex-wake))
383 (define-alien-routine ("futex_wait" %futex-wait) int
384 (word unsigned) (old-value unsigned)
385 (to-sec long) (to-usec unsigned-long))
387 (defun futex-wait (word old to-sec to-usec)
388 (with-interrupts
389 (%futex-wait word old to-sec to-usec)))
391 (define-alien-routine "futex_wake"
392 int (word unsigned) (n unsigned-long))))
394 ;;; used by debug-int.lisp to access interrupt contexts
396 ;;; The two uses immediately below of (unsigned-byte 27) are arbitrary,
397 ;;; as a more reasonable type restriction is an integer from 0 to
398 ;;; (+ (primitive-object-size
399 ;;; (find 'thread *primitive-objects* :key #'primitive-object-name))
400 ;;; MAX-INTERRUPTS) ; defined only for C in 'interrupt.h'
402 ;;; The x86 32-bit port is helped slightly by having a stricter constraint
403 ;;; than the (unsigned-byte 32) from its DEFKNOWN of this function.
404 ;;; Ideally a single defknown would work for any backend because the thread
405 ;;; structure is, after all, defined in the generic objdefs. But the VM needs
406 ;;; the defknown before the VOP, and this file comes too late, so we'd
407 ;;; need to pick some other place - maybe 'thread.lisp'?
409 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
410 #!-sb-thread
411 (defun sb!vm::current-thread-offset-sap (n)
412 (declare (type (unsigned-byte 27) n))
413 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
414 (* n sb!vm:n-word-bytes)))
416 #!+sb-thread
417 (defun sb!vm::current-thread-offset-sap (n)
418 (declare (type (unsigned-byte 27) n))
419 (sb!vm::current-thread-offset-sap n))
422 (defmacro with-deadlocks ((thread lock &optional (timeout nil timeoutp)) &body forms)
423 (with-unique-names (n-thread n-lock new n-timeout)
424 `(let* ((,n-thread ,thread)
425 (,n-lock ,lock)
426 (,n-timeout ,(when timeoutp
427 `(or ,timeout
428 (when sb!impl::*deadline*
429 sb!impl::*deadline-seconds*))))
430 (,new (if ,n-timeout
431 ;; Using CONS tells the rest of the system there's a
432 ;; timeout in place, so it isn't considered a deadlock.
433 (cons ,n-timeout ,n-lock)
434 ,n-lock)))
435 (declare (dynamic-extent ,new))
436 ;; No WITHOUT-INTERRUPTS, since WITH-DEADLOCKS is used
437 ;; in places where interrupts should already be disabled.
438 (unwind-protect
439 (progn
440 (setf (thread-waiting-for ,n-thread) ,new)
441 (barrier (:write))
442 ,@forms)
443 ;; Interrupt handlers and GC save and restore any
444 ;; previous wait marks using WITHOUT-DEADLOCKS below.
445 (setf (thread-waiting-for ,n-thread) nil)
446 (barrier (:write))))))
448 ;;;; Mutexes
450 #!+sb-doc
451 (setf (fdocumentation 'make-mutex 'function)
452 "Create a mutex."
453 (fdocumentation 'mutex-name 'function)
454 "The name of the mutex. Setfable.")
456 #!+(and sb-thread sb-futex)
457 (progn
458 (define-structure-slot-addressor mutex-state-address
459 :structure mutex
460 :slot state)
461 ;; Important: current code assumes these are fixnums or other
462 ;; lisp objects that don't need pinning.
463 (defconstant +lock-free+ 0)
464 (defconstant +lock-taken+ 1)
465 (defconstant +lock-contested+ 2))
467 (defun mutex-owner (mutex)
468 #!+sb-doc
469 "Current owner of the mutex, NIL if the mutex is free. Naturally,
470 this is racy by design (another thread may acquire the mutex after
471 this function returns), it is intended for informative purposes. For
472 testing whether the current thread is holding a mutex see
473 HOLDING-MUTEX-P."
474 ;; Make sure to get the current value.
475 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
477 (sb!ext:defglobal **deadlock-lock** nil)
479 ;;; Signals an error if owner of LOCK is waiting on a lock whose release
480 ;;; depends on the current thread. Does not detect deadlocks from sempahores.
481 (defun check-deadlock ()
482 (let* ((self *current-thread*)
483 (origin (progn
484 (barrier (:read))
485 (thread-waiting-for self))))
486 (labels ((detect-deadlock (lock)
487 (let ((other-thread (mutex-%owner lock)))
488 (cond ((not other-thread))
489 ((eq self other-thread)
490 (let ((chain
491 (with-cas-lock ((symbol-value '**deadlock-lock**))
492 (prog1 (deadlock-chain self origin)
493 ;; We're now committed to signaling the
494 ;; error and breaking the deadlock, so
495 ;; mark us as no longer waiting on the
496 ;; lock. This ensures that a single
497 ;; deadlock is reported in only one
498 ;; thread, and that we don't look like
499 ;; we're waiting on the lock when print
500 ;; stuff -- because that may lead to
501 ;; further deadlock checking, in turn
502 ;; possibly leading to a bogus vicious
503 ;; metacycle on PRINT-OBJECT.
504 (setf (thread-waiting-for self) nil)))))
505 (error 'thread-deadlock
506 :thread *current-thread*
507 :cycle chain)))
509 (let ((other-lock (progn
510 (barrier (:read))
511 (thread-waiting-for other-thread))))
512 ;; If the thread is waiting with a timeout OTHER-LOCK
513 ;; is a cons, and we don't consider it a deadlock -- since
514 ;; it will time out on its own sooner or later.
515 (when (mutex-p other-lock)
516 (detect-deadlock other-lock)))))))
517 (deadlock-chain (thread lock)
518 (let* ((other-thread (mutex-owner lock))
519 (other-lock (when other-thread
520 (barrier (:read))
521 (thread-waiting-for other-thread))))
522 (cond ((not other-thread)
523 ;; The deadlock is gone -- maybe someone unwound
524 ;; from the same deadlock already?
525 (return-from check-deadlock nil))
526 ((consp other-lock)
527 ;; There's a timeout -- no deadlock.
528 (return-from check-deadlock nil))
529 ((waitqueue-p other-lock)
530 ;; Not a lock.
531 (return-from check-deadlock nil))
532 ((eq self other-thread)
533 ;; Done
534 (list (list thread lock)))
536 (if other-lock
537 (cons (cons thread lock)
538 (deadlock-chain other-thread other-lock))
539 ;; Again, the deadlock is gone?
540 (return-from check-deadlock nil)))))))
541 ;; Timeout means there is no deadlock
542 (when (mutex-p origin)
543 (detect-deadlock origin)
544 t))))
546 (defun %try-mutex (mutex new-owner)
547 (declare (type mutex mutex) (optimize (speed 3)))
548 (barrier (:read))
549 (let ((old (mutex-%owner mutex)))
550 (when (eq new-owner old)
551 (error "Recursive lock attempt ~S." mutex))
552 #!-sb-thread
553 (when old
554 (error "Strange deadlock on ~S in an unithreaded build?" mutex))
555 #!-(and sb-thread sb-futex)
556 (and (not old)
557 ;; Don't even bother to try to CAS if it looks bad.
558 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
559 #!+(and sb-thread sb-futex)
560 ;; From the Mutex 2 algorithm from "Futexes are Tricky" by Ulrich Drepper.
561 (when (eql +lock-free+ (sb!ext:compare-and-swap (mutex-state mutex)
562 +lock-free+
563 +lock-taken+))
564 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex) nil new-owner)))
565 (when prev
566 (bug "Old owner in free mutex: ~S" prev))
567 t))))
569 #!+sb-thread
570 (defun %%wait-for-mutex (mutex new-owner to-sec to-usec stop-sec stop-usec)
571 (declare (type mutex mutex) (optimize (speed 3)))
572 #!-sb-futex
573 (declare (ignore to-sec to-usec))
574 #!-sb-futex
575 (flet ((cas ()
576 (loop repeat 100
577 when (and (progn
578 (barrier (:read))
579 (not (mutex-%owner mutex)))
580 (not (sb!ext:compare-and-swap (mutex-%owner mutex) nil
581 new-owner)))
582 do (return-from cas t)
583 else
585 (sb!ext:spin-loop-hint))
586 ;; Check for pending interrupts.
587 (with-interrupts nil)))
588 (declare (dynamic-extent #'cas))
589 (sb!impl::%%wait-for #'cas stop-sec stop-usec))
590 #!+sb-futex
591 ;; This is a fairly direct translation of the Mutex 2 algorithm from
592 ;; "Futexes are Tricky" by Ulrich Drepper.
593 (flet ((maybe (old)
594 (when (eql +lock-free+ old)
595 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
596 nil new-owner)))
597 (when prev
598 (bug "Old owner in free mutex: ~S" prev))
599 (return-from %%wait-for-mutex t)))))
600 (prog ((old (sb!ext:compare-and-swap (mutex-state mutex)
601 +lock-free+ +lock-taken+)))
602 ;; Got it right off the bat?
603 (maybe old)
604 :retry
605 ;; Mark it as contested, and sleep. (Exception: it was just released.)
606 (when (or (eql +lock-contested+ old)
607 (not (eql +lock-free+
608 (sb!ext:compare-and-swap
609 (mutex-state mutex) +lock-taken+ +lock-contested+))))
610 (when (eql 1 (with-pinned-objects (mutex)
611 (futex-wait (mutex-state-address mutex)
612 (get-lisp-obj-address +lock-contested+)
613 (or to-sec -1)
614 (or to-usec 0))))
615 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
616 ;; 0 = normal wakeup
617 ;; 1 = ETIMEDOUT ***DONE***
618 ;; 2 = EINTR, a spurious wakeup
619 (return-from %%wait-for-mutex nil)))
620 ;; Try to get it, still marking it as contested.
621 (maybe
622 (sb!ext:compare-and-swap (mutex-state mutex) +lock-free+ +lock-contested+))
623 ;; Update timeout if necessary.
624 (when stop-sec
625 (setf (values to-sec to-usec)
626 (sb!impl::relative-decoded-times stop-sec stop-usec)))
627 ;; Spin.
628 (go :retry))))
630 #!+sb-thread
631 (defun %wait-for-mutex (mutex self timeout to-sec to-usec stop-sec stop-usec deadlinep)
632 (with-deadlocks (self mutex timeout)
633 (with-interrupts (check-deadlock))
634 (tagbody
635 :again
636 (return-from %wait-for-mutex
637 (or (%%wait-for-mutex mutex self to-sec to-usec stop-sec stop-usec)
638 (when deadlinep
639 (signal-deadline)
640 ;; FIXME: substract elapsed time from timeout...
641 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
642 (decode-timeout timeout))
643 (go :again)))))))
645 (define-deprecated-function :early "1.0.37.33" get-mutex (grab-mutex)
646 (mutex &optional new-owner (waitp t) (timeout nil))
647 (declare (ignorable waitp timeout))
648 (let ((new-owner (or new-owner *current-thread*)))
649 (or (%try-mutex mutex new-owner)
650 #!+sb-thread
651 (when waitp
652 (multiple-value-call #'%wait-for-mutex
653 mutex new-owner timeout (decode-timeout timeout))))))
655 (defun grab-mutex (mutex &key (waitp t) (timeout nil))
656 #!+sb-doc
657 "Acquire MUTEX for the current thread. If WAITP is true (the default) and
658 the mutex is not immediately available, sleep until it is available.
660 If TIMEOUT is given, it specifies a relative timeout, in seconds, on how long
661 GRAB-MUTEX should try to acquire the lock in the contested case.
663 If GRAB-MUTEX returns T, the lock acquisition was successful. In case of WAITP
664 being NIL, or an expired TIMEOUT, GRAB-MUTEX may also return NIL which denotes
665 that GRAB-MUTEX did -not- acquire the lock.
667 Notes:
669 - GRAB-MUTEX is not interrupt safe. The correct way to call it is:
671 (WITHOUT-INTERRUPTS
673 (ALLOW-WITH-INTERRUPTS (GRAB-MUTEX ...))
674 ...)
676 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the call
677 while the mutex is in an inconsistent state while ALLOW-WITH-INTERRUPTS
678 allows the call to be interrupted from sleep.
680 - (GRAB-MUTEX <mutex> :timeout 0.0) differs from
681 (GRAB-MUTEX <mutex> :waitp nil) in that the former may signal a
682 DEADLINE-TIMEOUT if the global deadline was due already on entering
683 GRAB-MUTEX.
685 The exact interplay of GRAB-MUTEX and deadlines are reserved to change in
686 future versions.
688 - It is recommended that you use WITH-MUTEX instead of calling GRAB-MUTEX
689 directly.
691 (declare (ignorable waitp timeout))
692 (let ((self *current-thread*))
693 (or (%try-mutex mutex self)
694 #!+sb-thread
695 (when waitp
696 (multiple-value-call #'%wait-for-mutex
697 mutex self timeout (decode-timeout timeout))))))
699 (defun release-mutex (mutex &key (if-not-owner :punt))
700 #!+sb-doc
701 "Release MUTEX by setting it to NIL. Wake up threads waiting for
702 this mutex.
704 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
705 around calls to it.
707 If the current thread is not the owner of the mutex then it silently
708 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
709 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
710 IF-NOT-OWNER is :FORCE)."
711 (declare (type mutex mutex))
712 ;; Order matters: set owner to NIL before releasing state.
713 (let* ((self *current-thread*)
714 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
715 (unless (eq self old-owner)
716 (ecase if-not-owner
717 ((:punt) (return-from release-mutex nil))
718 ((:warn)
719 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
720 ((:force)))
721 (setf (mutex-%owner mutex) nil)
722 ;; FIXME: Is a :memory barrier too strong here? Can we use a :write
723 ;; barrier instead?
724 (barrier (:memory)))
725 #!+(and sb-thread sb-futex)
726 (when old-owner
727 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
728 ;; unsigned-byte type this can be used:
730 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
731 ;; (unless (eql old +lock-free+)
732 ;; (setf (mutex-state mutex) +lock-free+)
733 ;; (with-pinned-objects (mutex)
734 ;; (futex-wake (mutex-state-address mutex) 1))))
735 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
736 +lock-taken+ +lock-free+)))
737 (when (eql old +lock-contested+)
738 (sb!ext:compare-and-swap (mutex-state mutex)
739 +lock-contested+ +lock-free+)
740 (with-pinned-objects (mutex)
741 (futex-wake (mutex-state-address mutex) 1))))
742 nil)))
745 ;;;; Waitqueues/condition variables
747 ;; For possible DX-allocating, see the notinline counterpart after the
748 ;; PROGN below
749 (declaim (inline make-waitqueue))
750 #!+(or (not sb-thread) sb-futex)
751 (defstruct (waitqueue (:constructor make-waitqueue (&key name)))
752 #!+sb-doc
753 "Waitqueue type."
754 (name nil :type (or null thread-name))
755 #!+(and sb-thread sb-futex)
756 (token nil))
758 #!+(and sb-thread (not sb-futex))
759 (progn
760 (defstruct (waitqueue (:constructor make-waitqueue (&key name)))
761 #!+sb-doc
762 "Waitqueue type."
763 (name nil :type (or null thread-name))
764 ;; For WITH-CAS-LOCK: because CONDITION-WAIT must be able to call
765 ;; %WAITQUEUE-WAKEUP without re-aquiring the mutex, we need a separate
766 ;; lock. In most cases this should be uncontested thanks to the mutex --
767 ;; the only case where that might not be true is when CONDITION-WAIT
768 ;; unwinds and %WAITQUEUE-DROP is called.
769 %owner
770 %head
771 %tail)
773 (defun %waitqueue-enqueue (thread queue)
774 (setf (thread-waiting-for thread) queue)
775 (let ((head (waitqueue-%head queue))
776 (tail (waitqueue-%tail queue))
777 (new (list thread)))
778 (unless head
779 (setf (waitqueue-%head queue) new))
780 (when tail
781 (setf (cdr tail) new))
782 (setf (waitqueue-%tail queue) new)
783 nil))
784 (defun %waitqueue-drop (thread queue)
785 (setf (thread-waiting-for thread) nil)
786 (let ((head (waitqueue-%head queue)))
787 (do ((list head (cdr list))
788 (prev nil list))
789 ((or (null list)
790 (eq (car list) thread))
791 (when list
792 (let ((rest (cdr list)))
793 (cond (prev
794 (setf (cdr prev) rest))
796 (setf (waitqueue-%head queue) rest
797 prev rest)))
798 (unless rest
799 (setf (waitqueue-%tail queue) prev)))))))
800 nil)
801 (defun %waitqueue-wakeup (queue n)
802 (declare (fixnum n))
803 (loop while (plusp n)
804 for next = (let ((head (waitqueue-%head queue))
805 (tail (waitqueue-%tail queue)))
806 (when head
807 (if (eq head tail)
808 (setf (waitqueue-%head queue) nil
809 (waitqueue-%tail queue) nil)
810 (setf (waitqueue-%head queue) (cdr head)))
811 (car head)))
812 while next
813 do (when (eq queue (sb!ext:compare-and-swap
814 (thread-waiting-for next) queue nil))
815 (decf n)))
816 nil))
817 (declaim (notinline make-waitqueue))
819 (def!method print-object ((waitqueue waitqueue) stream)
820 (print-unreadable-object (waitqueue stream :type t :identity t)
821 (format stream "~@[~A~]" (waitqueue-name waitqueue))))
823 #!+sb-doc
824 (setf (fdocumentation 'waitqueue-name 'function)
825 "The name of the waitqueue. Setfable."
826 (fdocumentation 'make-waitqueue 'function)
827 "Create a waitqueue.")
829 #!+(and sb-thread sb-futex)
830 (define-structure-slot-addressor waitqueue-token-address
831 :structure waitqueue
832 :slot token)
834 (declaim (inline %condition-wait))
835 (defun %condition-wait (queue mutex timeout to-sec to-usec stop-sec stop-usec deadlinep)
836 (let ((me *current-thread*))
837 (barrier (:read))
838 (assert (eq me (mutex-%owner mutex)))
839 (let ((status :interrupted))
840 ;; Need to disable interrupts so that we don't miss grabbing the
841 ;; mutex on our way out.
842 (without-interrupts
843 (unwind-protect
844 (progn
845 #!-sb-futex
846 (progn
847 (%with-cas-lock ((waitqueue-%owner queue))
848 (%waitqueue-enqueue me queue))
849 (release-mutex mutex)
850 (setf status
851 (or (flet ((wakeup ()
852 (barrier (:read))
853 (unless (eq queue (thread-waiting-for me))
854 :ok)))
855 (declare (dynamic-extent #'wakeup))
856 (allow-with-interrupts
857 (sb!impl::%%wait-for #'wakeup stop-sec stop-usec)))
858 :timeout)))
859 #!+sb-futex
860 (with-pinned-objects (queue me)
861 (setf (waitqueue-token queue) me)
862 (release-mutex mutex)
863 ;; Now we go to sleep using futex-wait. If anyone else
864 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
865 ;; this comment, it will change the token, and so futex-wait
866 ;; returns immediately instead of sleeping. Ergo, no lost
867 ;; wakeup. We may get spurious wakeups, but that's ok.
868 (setf status
869 (case (allow-with-interrupts
870 (futex-wait (waitqueue-token-address queue)
871 (get-lisp-obj-address me)
872 ;; our way of saying "no
873 ;; timeout":
874 (or to-sec -1)
875 (or to-usec 0)))
876 ((1)
877 ;; 1 = ETIMEDOUT
878 :timeout)
880 ;; -1 = EWOULDBLOCK, possibly spurious wakeup
881 ;; 0 = normal wakeup
882 ;; 2 = EINTR, a spurious wakeup
883 :ok)))))
884 #!-sb-futex
885 (%with-cas-lock ((waitqueue-%owner queue))
886 (if (eq queue (thread-waiting-for me))
887 (%waitqueue-drop me queue)
888 (unless (eq :ok status)
889 ;; CONDITION-NOTIFY thinks we've been woken up, but really
890 ;; we're unwinding. Wake someone else up.
891 (%waitqueue-wakeup queue 1))))
892 ;; Update timeout for mutex re-aquisition unless we are
893 ;; already past the requested timeout.
894 (when (and (eq :ok status) to-sec)
895 (setf (values to-sec to-usec)
896 (sb!impl::relative-decoded-times stop-sec stop-usec))
897 (when (and (zerop to-sec) (not (plusp to-usec)))
898 (setf status :timeout)))
899 ;; If we ran into deadline, try to get the mutex before
900 ;; signaling. If we don't unwind it will look like a normal
901 ;; return from user perspective.
902 (when (and (eq :timeout status) deadlinep)
903 (let ((got-it (%try-mutex mutex me)))
904 (allow-with-interrupts
905 (signal-deadline)
906 (cond (got-it
907 (return-from %condition-wait t))
909 ;; The deadline may have changed.
910 (setf (values to-sec to-usec stop-sec stop-usec deadlinep)
911 (decode-timeout timeout))
912 (setf status :ok))))))
913 ;; Re-acquire the mutex for normal return.
914 (when (eq :ok status)
915 (unless (or (%try-mutex mutex me)
916 (allow-with-interrupts
917 (%wait-for-mutex mutex me timeout
918 to-sec to-usec
919 stop-sec stop-usec deadlinep)))
920 (setf status :timeout)))))
921 ;; Determine actual return value. :ok means (potentially
922 ;; spurious) wakeup => T. :timeout => NIL.
923 (case status
924 (:ok
925 (if timeout
926 (multiple-value-bind (sec usec)
927 (sb!impl::relative-decoded-times stop-sec stop-usec)
928 (values t sec usec))
930 (:timeout
931 nil)
933 ;; The only case we return normally without re-acquiring
934 ;; the mutex is when there is a :TIMEOUT that runs out.
935 (bug "%CONDITION-WAIT: invalid status on normal return: ~S" status))))))
936 (declaim (notinline %condition-wait))
938 (defun condition-wait (queue mutex &key timeout)
939 #!+sb-doc
940 "Atomically release MUTEX and start waiting on QUEUE for till another thread
941 wakes us up using either CONDITION-NOTIFY or CONDITION-BROADCAST on that
942 queue, at which point we re-acquire MUTEX and return T.
944 Spurious wakeups are possible.
946 If TIMEOUT is given, it is the maximum number of seconds to wait, including
947 both waiting for the wakeup and the time to re-acquire MUTEX. Unless both
948 wakeup and re-acquisition do not occur within the given time, returns NIL
949 without re-acquiring the mutex.
951 If CONDITION-WAIT unwinds, it may do so with or without the mutex being held.
953 Important: Since CONDITION-WAIT may return without CONDITION-NOTIFY having
954 occurred the correct way to write code that uses CONDITION-WAIT is to loop
955 around the call, checking the the associated data:
957 (defvar *data* nil)
958 (defvar *queue* (make-waitqueue))
959 (defvar *lock* (make-mutex))
961 ;; Consumer
962 (defun pop-data (&optional timeout)
963 (with-mutex (*lock*)
964 (loop until *data*
965 do (or (condition-wait *queue* *lock* :timeout timeout)
966 ;; Lock not held, must unwind without touching *data*.
967 (return-from pop-data nil)))
968 (pop *data*)))
970 ;; Producer
971 (defun push-data (data)
972 (with-mutex (*lock*)
973 (push data *data*)
974 (condition-notify *queue*)))
976 #!-sb-thread
977 (declare (ignore queue))
978 (assert mutex)
979 #!-sb-thread
980 (sb!ext:wait-for nil :timeout timeout) ; Yeah...
981 #!+sb-thread
982 (locally (declare (inline %condition-wait))
983 (multiple-value-bind (to-sec to-usec stop-sec stop-usec deadlinep)
984 (decode-timeout timeout)
985 (%condition-wait queue mutex timeout
986 to-sec to-usec stop-sec stop-usec deadlinep))))
988 (defun condition-notify (queue &optional (n 1))
989 #!+sb-doc
990 "Notify N threads waiting on QUEUE.
992 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
993 must be held by this thread during this call."
994 #!-sb-thread
995 (declare (ignore queue n))
996 #!-sb-thread
997 (error "Not supported in unithread builds.")
998 #!+sb-thread
999 (declare (type (and fixnum (integer 1)) n))
1000 (/show0 "Entering CONDITION-NOTIFY")
1001 #!+sb-thread
1002 (progn
1003 #!-sb-futex
1004 (with-cas-lock ((waitqueue-%owner queue))
1005 (%waitqueue-wakeup queue n))
1006 #!+sb-futex
1007 (progn
1008 ;; No problem if >1 thread notifies during the comment in condition-wait:
1009 ;; as long as the value in queue-data isn't the waiting thread's id, it
1010 ;; matters not what it is -- using the queue object itself is handy.
1012 ;; XXX we should do something to ensure that the result of this setf
1013 ;; is visible to all CPUs.
1015 ;; ^-- surely futex_wake() involves a memory barrier?
1016 (setf (waitqueue-token queue) queue)
1017 (with-pinned-objects (queue)
1018 (futex-wake (waitqueue-token-address queue) n)))))
1020 (defun condition-broadcast (queue)
1021 #!+sb-doc
1022 "Notify all threads waiting on QUEUE.
1024 IMPORTANT: The same mutex that is used in the corresponding CONDITION-WAIT
1025 must be held by this thread during this call."
1026 (condition-notify queue
1027 ;; On a 64-bit platform truncating M-P-F to an int
1028 ;; results in -1, which wakes up only one thread.
1029 (ldb (byte 29 0)
1030 most-positive-fixnum)))
1033 ;;;; Semaphores
1035 (declaim (inline make-semaphore)) ;; for possible DX-allocating
1036 (defstruct (semaphore (:constructor make-semaphore
1037 (&key name ((:count %count) 0))))
1038 #!+sb-doc
1039 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
1040 should be considered an implementation detail, and may change in the
1041 future."
1042 (name nil :type (or null thread-name))
1043 (%count 0 :type (integer 0))
1044 (waitcount 0 :type sb!vm:word)
1045 (mutex (make-mutex))
1046 (queue (make-waitqueue)))
1047 (declaim (notinline make-semaphore))
1049 #!+sb-doc
1050 (setf (fdocumentation 'semaphore-name 'function)
1051 "The name of the semaphore INSTANCE. Setfable."
1052 (fdocumentation 'make-semaphore 'function)
1053 "Create a semaphore with the supplied COUNT and NAME.")
1055 (defstruct (semaphore-notification (:constructor make-semaphore-notification ())
1056 (:copier nil))
1057 #!+sb-doc
1058 "Semaphore notification object. Can be passed to WAIT-ON-SEMAPHORE and
1059 TRY-SEMAPHORE as the :NOTIFICATION argument. Consequences are undefined if
1060 multiple threads are using the same notification object in parallel."
1061 (%status nil :type boolean))
1063 #!+sb-doc
1064 (setf (fdocumentation 'make-semaphore-notification 'function)
1065 "Constructor for SEMAPHORE-NOTIFICATION objects. SEMAPHORE-NOTIFICATION-STATUS
1066 is initially NIL.")
1068 (declaim (inline semaphore-notification-status))
1069 (defun semaphore-notification-status (semaphore-notification)
1070 #!+sb-doc
1071 "Returns T if a WAIT-ON-SEMAPHORE or TRY-SEMAPHORE using
1072 SEMAPHORE-NOTIFICATION has succeeded since the notification object was created
1073 or cleared."
1074 (barrier (:read))
1075 (semaphore-notification-%status semaphore-notification))
1077 (declaim (inline clear-semaphore-notification))
1078 (defun clear-semaphore-notification (semaphore-notification)
1079 #!+sb-doc
1080 "Resets the SEMAPHORE-NOTIFICATION object for use with another call to
1081 WAIT-ON-SEMAPHORE or TRY-SEMAPHORE."
1082 (barrier (:write)
1083 (setf (semaphore-notification-%status semaphore-notification) nil)))
1085 (declaim (inline semaphore-count))
1086 (defun semaphore-count (instance)
1087 #!+sb-doc
1088 "Returns the current count of the semaphore INSTANCE."
1089 (barrier (:read))
1090 (semaphore-%count instance))
1092 (declaim (ftype (sfunction (semaphore (integer 1) (or boolean real)
1093 (or null semaphore-notification) symbol)
1095 %decrement-semaphore))
1096 (defun %decrement-semaphore (semaphore n wait notification context)
1097 (when (and notification (semaphore-notification-status notification))
1098 (with-simple-restart (continue "Clear notification status and continue.")
1099 (error "~@<Semaphore notification object status not cleared on ~
1100 entry to ~S on ~S.~:@>"
1101 context semaphore))
1102 (clear-semaphore-notification notification))
1104 ;; A more direct implementation based directly on futexes should be
1105 ;; possible.
1107 ;; We need to disable interrupts so that we don't forget to
1108 ;; decrement the waitcount (which would happen if an asynch
1109 ;; interrupt should catch us on our way out from the loop.)
1111 ;; FIXME: No timeout on initial mutex acquisition.
1112 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1113 (flet ((success (new-count)
1114 (prog1
1115 (setf (semaphore-%count semaphore) new-count)
1116 (when notification
1117 (setf (semaphore-notification-%status notification) t)))))
1118 ;; Quick check: can we decrement right away? If not, return or
1119 ;; enter the wait loop.
1120 (cond
1121 ((let ((old-count (semaphore-%count semaphore)))
1122 (when (>= old-count n)
1123 (success (- old-count n)))))
1124 ((not wait)
1125 nil)
1127 (unwind-protect
1128 (binding* ((old-count nil)
1129 (timeout (when (realp wait) wait))
1130 ((to-sec to-usec stop-sec stop-usec deadlinep)
1131 (when wait
1132 (decode-timeout timeout))))
1133 ;; Need to use ATOMIC-INCF despite the lock, because
1134 ;; on our way out from here we might not be locked
1135 ;; anymore -- so another thread might be tweaking this
1136 ;; in parallel using ATOMIC-DECF. No danger over
1137 ;; overflow, since there it at most one increment per
1138 ;; thread waiting on the semaphore.
1139 (sb!ext:atomic-incf (semaphore-waitcount semaphore))
1140 (loop until (>= (setf old-count (semaphore-%count semaphore)) n)
1141 do (multiple-value-bind (wakeup-p remaining-sec remaining-usec)
1142 (%condition-wait
1143 (semaphore-queue semaphore)
1144 (semaphore-mutex semaphore)
1145 timeout to-sec to-usec stop-sec stop-usec deadlinep)
1146 (when (or (not wakeup-p)
1147 (and (eql remaining-sec 0)
1148 (eql remaining-usec 0)))
1149 (return-from %decrement-semaphore nil)) ; timeout
1150 (when remaining-sec
1151 (setf to-sec remaining-sec
1152 to-usec remaining-usec))))
1153 (success (- old-count n)))
1154 ;; Need to use ATOMIC-DECF as we may unwind without the
1155 ;; lock being held!
1156 (sb!ext:atomic-decf (semaphore-waitcount semaphore))))))))
1158 (declaim (ftype (sfunction (semaphore &key
1159 (:n (integer 1))
1160 (:timeout (real (0)))
1161 (:notification semaphore-notification))
1162 (or null (integer 0)))
1163 wait-on-semaphore))
1164 (defun wait-on-semaphore (semaphore &key (n 1) timeout notification)
1165 #!+sb-doc
1166 "Decrement the count of SEMAPHORE by N if the count would not be negative.
1168 Else blocks until the semaphore can be decremented. Returns the new count of
1169 SEMAPHORE on success.
1171 If TIMEOUT is given, it is the maximum number of seconds to wait. If the count
1172 cannot be decremented in that time, returns NIL without decrementing the
1173 count.
1175 If NOTIFICATION is given, it must be a SEMAPHORE-NOTIFICATION object whose
1176 SEMAPHORE-NOTIFICATION-STATUS is NIL. If WAIT-ON-SEMAPHORE succeeds and
1177 decrements the count, the status is set to T."
1178 (%decrement-semaphore
1179 semaphore n (or timeout t) notification 'wait-on-semaphore))
1181 (declaim (ftype (sfunction (semaphore &optional
1182 (integer 1) semaphore-notification)
1183 (or null (integer 0)))
1184 try-semaphore))
1185 (defun try-semaphore (semaphore &optional (n 1) notification)
1186 #!+sb-doc
1187 "Try to decrement the count of SEMAPHORE by N. If the count were to
1188 become negative, punt and return NIL, otherwise return the new count of
1189 SEMAPHORE.
1191 If NOTIFICATION is given it must be a semaphore notification object
1192 with SEMAPHORE-NOTIFICATION-STATUS of NIL. If the count is decremented,
1193 the status is set to T."
1194 (%decrement-semaphore semaphore n nil notification 'try-semaphore))
1196 (defun signal-semaphore (semaphore &optional (n 1))
1197 #!+sb-doc
1198 "Increment the count of SEMAPHORE by N. If there are threads waiting
1199 on this semaphore, then N of them is woken up."
1200 (declare (type (integer 1) n))
1201 ;; Need to disable interrupts so that we don't lose a wakeup after
1202 ;; we have incremented the count.
1203 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
1204 (let ((waitcount (semaphore-waitcount semaphore))
1205 (count (incf (semaphore-%count semaphore) n)))
1206 (when (plusp waitcount)
1207 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
1210 ;;;; Job control, independent listeners
1212 (defstruct session
1213 (lock (make-mutex :name "session lock"))
1214 (threads nil)
1215 (interactive-threads nil)
1216 (interactive-threads-queue (make-waitqueue)))
1218 (defvar *session* nil)
1220 ;;; The debugger itself tries to acquire the session lock, don't let
1221 ;;; funny situations (like getting a sigint while holding the session
1222 ;;; lock) occur. At the same time we need to allow interrupts while
1223 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
1224 ;;; be interruptible.
1226 ;;; Take care: we sometimes need to obtain the session lock while
1227 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
1228 ;;; _after_ getting a session lock! (Deadlock risk.)
1230 ;;; FIXME: It would be good to have ordered locks to ensure invariants
1231 ;;; like the above.
1232 (defmacro with-session-lock ((session) &body body)
1233 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
1234 ,@body))
1236 (defun new-session ()
1237 (make-session :threads (list *current-thread*)
1238 :interactive-threads (list *current-thread*)))
1240 (defun init-job-control ()
1241 (/show0 "Entering INIT-JOB-CONTROL")
1242 (setf *session* (new-session))
1243 (/show0 "Exiting INIT-JOB-CONTROL"))
1245 (defun %delete-thread-from-session (thread session)
1246 (with-session-lock (session)
1247 (setf (session-threads session)
1248 ;; DELQ never conses, but DELETE does. (FIXME)
1249 (delq thread (session-threads session))
1250 (session-interactive-threads session)
1251 (delq thread (session-interactive-threads session)))))
1253 (defun call-with-new-session (fn)
1254 (%delete-thread-from-session *current-thread* *session*)
1255 (let ((*session* (new-session)))
1256 (funcall fn)))
1258 (defmacro with-new-session (args &body forms)
1259 (declare (ignore args)) ;for extensibility
1260 (sb!int:with-unique-names (fb-name)
1261 `(labels ((,fb-name () ,@forms))
1262 (call-with-new-session (function ,fb-name)))))
1264 ;;; Remove thread from its session, if it has one.
1265 #!+sb-thread
1266 (defun handle-thread-exit (thread)
1267 (/show0 "HANDLING THREAD EXIT")
1268 (when *exit-in-process*
1269 (%exit))
1270 ;; Lisp-side cleanup
1271 (with-all-threads-lock
1272 (setf (thread-%alive-p thread) nil)
1273 (setf (thread-os-thread thread) 0)
1274 (setq *all-threads* (delq thread *all-threads*))
1275 (when *session*
1276 (%delete-thread-from-session thread *session*))))
1278 (defun %exit-other-threads ()
1279 ;; Grabbing this lock prevents new threads from
1280 ;; being spawned, and guarantees that *ALL-THREADS*
1281 ;; is up to date.
1282 (with-deadline (:seconds nil :override t)
1283 (grab-mutex *make-thread-lock*)
1284 (let ((timeout sb!ext:*exit-timeout*)
1285 (code *exit-in-process*)
1286 (current *current-thread*)
1287 (joinees nil)
1288 (main nil))
1289 (dolist (thread (list-all-threads))
1290 (cond ((eq thread current))
1291 ((main-thread-p thread)
1292 (setf main thread))
1294 (handler-case
1295 (progn
1296 (terminate-thread thread)
1297 (push thread joinees))
1298 (interrupt-thread-error ())))))
1299 (with-progressive-timeout (time-left :seconds timeout)
1300 (dolist (thread joinees)
1301 (join-thread thread :default t :timeout (time-left)))
1302 ;; Need to defer till others have joined, because when main
1303 ;; thread exits, we're gone. Can't use TERMINATE-THREAD -- would
1304 ;; get the exit code wrong.
1305 (when main
1306 (handler-case
1307 (interrupt-thread
1308 main
1309 (lambda ()
1310 (setf *exit-in-process* (list code))
1311 (throw 'sb!impl::%end-of-the-world t)))
1312 (interrupt-thread-error ()))
1313 ;; Normally this never finishes, as once the main-thread unwinds we
1314 ;; exit with the right code, but if times out before that happens,
1315 ;; we will exit after returning -- or rathe racing the main thread
1316 ;; to calling OS-EXIT.
1317 (join-thread main :default t :timeout (time-left)))))))
1319 (defun terminate-session ()
1320 #!+sb-doc
1321 "Kill all threads in session except for this one. Does nothing if current
1322 thread is not the foreground thread."
1323 ;; FIXME: threads created in other threads may escape termination
1324 (let ((to-kill
1325 (with-session-lock (*session*)
1326 (and (eq *current-thread*
1327 (car (session-interactive-threads *session*)))
1328 (session-threads *session*)))))
1329 ;; do the kill after dropping the mutex; unwind forms in dying
1330 ;; threads may want to do session things
1331 (dolist (thread to-kill)
1332 (unless (eq thread *current-thread*)
1333 ;; terminate the thread but don't be surprised if it has
1334 ;; exited in the meantime
1335 (handler-case (terminate-thread thread)
1336 (interrupt-thread-error ()))))))
1338 ;;; called from top of invoke-debugger
1339 (defun debugger-wait-until-foreground-thread (stream)
1340 #!+sb-doc
1341 "Returns T if thread had been running in background, NIL if it was
1342 interactive."
1343 (declare (ignore stream))
1344 #!-sb-thread nil
1345 #!+sb-thread
1346 (prog1
1347 (with-session-lock (*session*)
1348 (not (member *current-thread*
1349 (session-interactive-threads *session*))))
1350 (get-foreground)))
1352 (defun get-foreground ()
1353 #!-sb-thread t
1354 #!+sb-thread
1355 (let ((was-foreground t))
1356 (loop
1357 (/show0 "Looping in GET-FOREGROUND")
1358 (with-session-lock (*session*)
1359 (let ((int-t (session-interactive-threads *session*)))
1360 (when (eq (car int-t) *current-thread*)
1361 (unless was-foreground
1362 (format *query-io* "Resuming thread ~A~%" *current-thread*))
1363 (return-from get-foreground t))
1364 (setf was-foreground nil)
1365 (unless (member *current-thread* int-t)
1366 (setf (cdr (last int-t))
1367 (list *current-thread*)))
1368 (condition-wait
1369 (session-interactive-threads-queue *session*)
1370 (session-lock *session*)))))))
1372 (defun release-foreground (&optional next)
1373 #!+sb-doc
1374 "Background this thread. If NEXT is supplied, arrange for it to
1375 have the foreground next."
1376 #!-sb-thread (declare (ignore next))
1377 #!-sb-thread nil
1378 #!+sb-thread
1379 (with-session-lock (*session*)
1380 (when (rest (session-interactive-threads *session*))
1381 (setf (session-interactive-threads *session*)
1382 (delete *current-thread* (session-interactive-threads *session*))))
1383 (when next
1384 (setf (session-interactive-threads *session*)
1385 (list* next
1386 (delete next (session-interactive-threads *session*)))))
1387 (condition-broadcast (session-interactive-threads-queue *session*))))
1389 (defun interactive-threads (&optional (session *session*))
1390 #!+sb-doc
1391 "Return the interactive threads of SESSION defaulting to the current
1392 session."
1393 (session-interactive-threads session))
1395 (defun foreground-thread (&optional (session *session*))
1396 #!+sb-doc
1397 "Return the foreground thread of SESSION defaulting to the current
1398 session."
1399 (first (interactive-threads session)))
1401 (defun make-listener-thread (tty-name)
1402 (assert (probe-file tty-name))
1403 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
1404 (out (sb!unix:unix-dup in))
1405 (err (sb!unix:unix-dup in)))
1406 (labels ((thread-repl ()
1407 (sb!unix::unix-setsid)
1408 (let* ((sb!impl::*stdin*
1409 (make-fd-stream in :input t :buffering :line
1410 :dual-channel-p t))
1411 (sb!impl::*stdout*
1412 (make-fd-stream out :output t :buffering :line
1413 :dual-channel-p t))
1414 (sb!impl::*stderr*
1415 (make-fd-stream err :output t :buffering :line
1416 :dual-channel-p t))
1417 (sb!impl::*tty*
1418 (make-fd-stream err :input t :output t
1419 :buffering :line
1420 :dual-channel-p t))
1421 (sb!impl::*descriptor-handlers* nil))
1422 (with-new-session ()
1423 (unwind-protect
1424 (sb!impl::toplevel-repl nil)
1425 (sb!int:flush-standard-output-streams))))))
1426 (make-thread #'thread-repl))))
1429 ;;;; The beef
1431 #!+sb-thread
1432 (defun initial-thread-function-trampoline
1433 (thread setup-sem real-function thread-list arguments arg1 arg2 arg3)
1434 ;; In time we'll move some of the binding presently done in C here
1435 ;; too.
1437 ;; KLUDGE: Here we have a magic list of variables that are not
1438 ;; thread-safe for one reason or another. As people report problems
1439 ;; with the thread safety of certain variables, (e.g. "*print-case* in
1440 ;; multiple threads broken", sbcl-devel 2006-07-14), we add a few more
1441 ;; bindings here. The Right Thing is probably some variant of
1442 ;; Allegro's *cl-default-special-bindings*, as that is at least
1443 ;; accessible to users to secure their own libraries.
1444 ;; --njf, 2006-07-15
1446 ;; As it is, this lambda must not cons until we are ready to run
1447 ;; GC. Be very careful.
1448 (let* ((*current-thread* thread)
1449 (*restart-clusters* nil)
1450 (*handler-clusters* sb!kernel::**initial-handler-clusters**)
1451 (*exit-in-process* nil)
1452 (sb!impl::*deadline* nil)
1453 (sb!impl::*deadline-seconds* nil)
1454 (sb!impl::*step-out* nil)
1455 ;; internal reader variables
1456 (sb!impl::*token-buf-pool* nil)
1457 ;; internal printer variables
1458 (sb!impl::*previous-case* nil)
1459 (sb!impl::*previous-readtable-case* nil)
1460 (sb!impl::*internal-symbol-output-fun* #'error)
1461 (sb!impl::*descriptor-handlers* nil)) ; serve-event
1462 (declare (inline make-restart)) ;; to allow DX-allocation
1463 ;; Binding from C
1464 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
1465 (setf (thread-os-thread thread) (current-thread-os-thread))
1466 (with-mutex ((thread-result-lock thread))
1467 ;; Normally the list is allocated in the parent thread to
1468 ;; avoid consing in a nascent thread.
1470 (let* ((thread-list (or thread-list
1471 (list thread thread)))
1472 (session-cons (cdr thread-list)))
1473 (with-all-threads-lock
1474 (setf (cdr thread-list) *all-threads*
1475 *all-threads* thread-list))
1476 (let ((session *session*))
1477 (with-session-lock (session)
1478 (setf (cdr session-cons) (session-threads session)
1479 (session-threads session) session-cons))))
1480 (setf (thread-%alive-p thread) t)
1482 (when setup-sem
1483 (signal-semaphore setup-sem)
1484 ;; setup-sem was dx-allocated, set it to NIL so that the
1485 ;; backtrace doesn't get confused
1486 (setf setup-sem nil))
1488 ;; Using handling-end-of-the-world would be a bit tricky
1489 ;; due to other catches and interrupts, so we essentially
1490 ;; re-implement it here. Once and only once more.
1491 (catch 'sb!impl::toplevel-catcher
1492 (catch 'sb!impl::%end-of-the-world
1493 (catch '%abort-thread
1494 (restart-bind ((abort
1495 (lambda ()
1496 (throw '%abort-thread nil))
1497 :report-function
1498 (lambda (stream)
1499 (format stream "~@<abort thread (~a)~@:>"
1500 *current-thread*))))
1501 (without-interrupts
1502 (unwind-protect
1503 (with-local-interrupts
1504 (setf *gc-inhibit* nil) ;for foreign callbacks
1505 (sb!unix::unblock-deferrable-signals)
1506 (setf (thread-result thread)
1507 (prog1
1508 (multiple-value-list
1509 (unwind-protect
1510 (catch '%return-from-thread
1511 (if (listp arguments)
1512 (apply real-function arguments)
1513 (funcall real-function arg1 arg2 arg3)))
1514 (when *exit-in-process*
1515 (sb!impl::call-exit-hooks))))
1516 #!+sb-safepoint
1517 (sb!kernel::gc-safepoint))))
1518 ;; we're going down, can't handle interrupts
1519 ;; sanely anymore. gc remains enabled.
1520 (block-deferrable-signals)
1521 ;; we don't want to run interrupts in a dead
1522 ;; thread when we leave without-interrupts.
1523 ;; this potentially causes important
1524 ;; interupts to be lost: sigint comes to
1525 ;; mind.
1526 (setq *interrupt-pending* nil)
1527 #!+sb-thruption
1528 (setq *thruption-pending* nil)
1529 (handle-thread-exit thread)))))))))
1530 (values))
1532 (defun make-thread (function &key name arguments ephemeral)
1533 #!+sb-doc
1534 "Create a new thread of NAME that runs FUNCTION with the argument
1535 list designator provided (defaults to no argument). Thread exits when
1536 the function returns. The return values of FUNCTION are kept around
1537 and can be retrieved by JOIN-THREAD.
1539 Invoking the initial ABORT restart established by MAKE-THREAD
1540 terminates the thread.
1542 See also: RETURN-FROM-THREAD, ABORT-THREAD."
1543 #!-sb-thread (declare (ignore function name arguments ephemeral))
1544 #!-sb-thread (error "Not supported in unithread builds.")
1545 #!+sb-thread (assert (or (atom arguments)
1546 (null (cdr (last arguments))))
1547 (arguments)
1548 "Argument passed to ~S, ~S, is an improper list."
1549 'make-thread arguments)
1550 #!+sb-thread
1551 (let ((thread (%make-thread :name name :%ephemeral-p ephemeral)))
1552 (declare (inline make-semaphore
1553 make-waitqueue
1554 make-mutex))
1555 (let* ((setup-sem (make-semaphore :name "Thread setup semaphore"))
1556 (real-function (coerce function 'function))
1557 (arguments (ensure-list arguments))
1558 #!+win32
1559 (fp-modes (dpb 0 sb!vm::float-sticky-bits ;; clear accrued bits
1560 (sb!vm:floating-point-modes)))
1561 ;; Allocate in the parent
1562 (thread-list (list thread thread)))
1563 (declare (dynamic-extent setup-sem))
1564 (dx-flet ((initial-thread-function ()
1565 ;; Win32 doesn't inherit parent thread's FP modes,
1566 ;; while it seems to happen everywhere else
1567 #!+win32
1568 (setf (sb!vm:floating-point-modes) fp-modes)
1569 ;; As it is, this lambda must not cons until we are
1570 ;; ready to run GC. Be very careful.
1571 (initial-thread-function-trampoline
1572 thread setup-sem real-function thread-list
1573 arguments nil nil nil)))
1574 ;; If the starting thread is stopped for gc before it signals
1575 ;; the semaphore then we'd be stuck.
1576 (assert (not *gc-inhibit*))
1577 ;; Keep INITIAL-FUNCTION in the dynamic extent until the child
1578 ;; thread is initialized properly. Wrap the whole thing in
1579 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to
1580 ;; another thread.
1581 (with-system-mutex (*make-thread-lock*)
1582 (if (zerop
1583 (%create-thread (get-lisp-obj-address #'initial-thread-function)))
1584 (setf thread nil)
1585 (wait-on-semaphore setup-sem)))))
1586 (or thread (error "Could not create a new thread."))))
1588 (defun join-thread (thread &key (default nil defaultp) timeout)
1589 #!+sb-doc
1590 "Suspend current thread until THREAD exits. Return the result values
1591 of the thread function.
1593 If the thread does not exit within TIMEOUT seconds and DEFAULT is
1594 supplied, return two values: 1) DEFAULT 2) :TIMEOUT. If DEFAULT is not
1595 supplied, signal a JOIN-THREAD-ERROR with JOIN-THREAD-ERROR-PROBLEM
1596 equal to :TIMEOUT.
1598 If the thread did not exit normally (i.e. aborted) and DEFAULT is
1599 supplied, return two values: 1) DEFAULT 2) :ABORT. If DEFAULT is not
1600 supplied, signal a JOIN-THREAD-THREAD-ERROR with problem equal
1601 to :ABORT.
1603 Trying to join the main thread will cause JOIN-THREAD to block until
1604 TIMEOUT occurs or the process exits: when main thread exits, the
1605 entire process exits.
1607 NOTE: Return convention in case of a timeout is experimental and
1608 subject to change."
1609 (let ((lock (thread-result-lock thread))
1610 (got-it nil)
1611 (problem :timeout))
1612 (without-interrupts
1613 (unwind-protect
1614 (cond
1615 ((not (setf got-it
1616 (allow-with-interrupts
1617 ;; Don't use the timeout if the thread is
1618 ;; not alive anymore.
1619 (grab-mutex lock :timeout (and (thread-alive-p thread)
1620 timeout))))))
1621 ((listp (thread-result thread))
1622 (return-from join-thread
1623 (values-list (thread-result thread))))
1625 (setf problem :abort)))
1626 (when got-it
1627 (release-mutex lock))))
1628 (if defaultp
1629 (values default problem)
1630 (error 'join-thread-error :thread thread :problem problem))))
1632 (defun destroy-thread (thread)
1633 (terminate-thread thread))
1635 #-sb-xc-host
1636 (declaim (sb!ext:deprecated
1637 :late ("SBCL" "1.2.15")
1638 (function destroy-thread :replacement terminate-thread)))
1640 #!+sb-thread
1641 (defun enter-foreign-callback (arg1 arg2 arg3)
1642 (initial-thread-function-trampoline
1643 (make-foreign-thread :name "foreign callback")
1644 nil #'sb!alien::enter-alien-callback nil t arg1 arg2 arg3))
1646 (defmacro with-interruptions-lock ((thread) &body body)
1647 `(with-system-mutex ((thread-interruptions-lock ,thread))
1648 ,@body))
1650 ;;; Called from the signal handler.
1651 #!-(or sb-thruption win32)
1652 (defun run-interruption ()
1653 (let ((interruption (with-interruptions-lock (*current-thread*)
1654 (pop (thread-interruptions *current-thread*)))))
1655 ;; If there is more to do, then resignal and let the normal
1656 ;; interrupt deferral mechanism take care of the rest. From the
1657 ;; OS's point of view the signal we are in the handler for is no
1658 ;; longer pending, so the signal will not be lost.
1659 (when (thread-interruptions *current-thread*)
1660 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
1661 (when interruption
1662 (funcall interruption))))
1664 #!+sb-thruption
1665 (defun run-interruption ()
1666 (in-interruption () ;the non-thruption code does this in the signal handler
1667 (let ((interruption (with-interruptions-lock (*current-thread*)
1668 (pop (thread-interruptions *current-thread*)))))
1669 (when interruption
1670 (funcall interruption)
1671 ;; I tried implementing this function as an explicit LOOP, because
1672 ;; if we are currently processing the thruption queue, why not do
1673 ;; all of them in one go instead of one-by-one?
1675 ;; I still think LOOPing would be basically the right thing
1676 ;; here. But suppose some interruption unblocked deferrables.
1677 ;; Will the next one be happy with that? The answer is "no", at
1678 ;; least in the sense that there are tests which check that
1679 ;; deferrables are blocked at the beginning of a thruption, and
1680 ;; races that make those tests fail. Whether the tests are
1681 ;; misguided or not, it seems easier/cleaner to loop implicitly
1682 ;; -- and it's also what AK had implemented in the first place.
1684 ;; The implicit loop is achieved by returning to C, but having C
1685 ;; call back to us immediately. The runtime will reset the sigmask
1686 ;; in the mean time.
1687 ;; -- DFL
1688 (setf *thruption-pending* t)))))
1690 (defun interrupt-thread (thread function)
1691 #!+sb-doc
1692 "Interrupt THREAD and make it run FUNCTION.
1694 The interrupt is asynchronous, and can occur anywhere with the exception of
1695 sections protected using SB-SYS:WITHOUT-INTERRUPTS.
1697 FUNCTION is called with interrupts disabled, under
1698 SB-SYS:ALLOW-WITH-INTERRUPTS. Since functions such as GRAB-MUTEX may try to
1699 enable interrupts internally, in most cases FUNCTION should either enter
1700 SB-SYS:WITH-INTERRUPTS to allow nested interrupts, or
1701 SB-SYS:WITHOUT-INTERRUPTS to prevent them completely.
1703 When a thread receives multiple interrupts, they are executed in the order
1704 they were sent -- first in, first out.
1706 This means that a great degree of care is required to use INTERRUPT-THREAD
1707 safely and sanely in a production environment. The general recommendation is
1708 to limit uses of INTERRUPT-THREAD for interactive debugging, banning it
1709 entirely from production environments -- it is simply exceedingly hard to use
1710 correctly.
1712 With those caveats in mind, what you need to know when using it:
1714 * If calling FUNCTION causes a non-local transfer of control (ie. an
1715 unwind), all normal cleanup forms will be executed.
1717 However, if the interrupt occurs during cleanup forms of an UNWIND-PROTECT,
1718 it is just as if that had happened due to a regular GO, THROW, or
1719 RETURN-FROM: the interrupted cleanup form and those following it in the
1720 same UNWIND-PROTECT do not get executed.
1722 SBCL tries to keep its own internals asynch-unwind-safe, but this is
1723 frankly an unreasonable expectation for third party libraries, especially
1724 given that asynch-unwind-safety does not compose: a function calling
1725 only asynch-unwind-safe function isn't automatically asynch-unwind-safe.
1727 This means that in order for an asynch unwind to be safe, the entire
1728 callstack at the point of interruption needs to be asynch-unwind-safe.
1730 * In addition to asynch-unwind-safety you must consider the issue of
1731 reentrancy. INTERRUPT-THREAD can cause function that are never normally
1732 called recursively to be re-entered during their dynamic contour,
1733 which may cause them to misbehave. (Consider binding of special variables,
1734 values of global variables, etc.)
1736 Take together, these two restrict the \"safe\" things to do using
1737 INTERRUPT-THREAD to a fairly minimal set. One useful one -- exclusively for
1738 interactive development use is using it to force entry to debugger to inspect
1739 the state of a thread:
1741 (interrupt-thread thread #'break)
1743 Short version: be careful out there."
1744 #!+(and (not sb-thread) win32)
1745 #!+(and (not sb-thread) win32)
1746 (declare (ignore thread))
1747 (with-interrupt-bindings
1748 (with-interrupts (funcall function)))
1749 #!-(and (not sb-thread) win32)
1750 (let ((os-thread (thread-os-thread thread)))
1751 (cond ((not os-thread)
1752 (error 'interrupt-thread-error :thread thread))
1754 (with-interruptions-lock (thread)
1755 ;; Append to the end of the interruptions queue. It's
1756 ;; O(N), but it does not hurt to slow interruptors down a
1757 ;; bit when the queue gets long.
1758 (setf (thread-interruptions thread)
1759 (append (thread-interruptions thread)
1760 (list (lambda ()
1761 (without-interrupts
1762 (allow-with-interrupts
1763 (funcall function))))))))
1764 (when (minusp (wake-thread os-thread))
1765 (error 'interrupt-thread-error :thread thread))))))
1767 (defun terminate-thread (thread)
1768 #!+sb-doc
1769 "Terminate the thread identified by THREAD, by interrupting it and
1770 causing it to call SB-EXT:ABORT-THREAD with :ALLOW-EXIT T.
1772 The unwind caused by TERMINATE-THREAD is asynchronous, meaning that
1773 eg. thread executing
1775 (let (foo)
1776 (unwind-protect
1777 (progn
1778 (setf foo (get-foo))
1779 (work-on-foo foo))
1780 (when foo
1781 ;; An interrupt occurring inside the cleanup clause
1782 ;; will cause cleanups from the current UNWIND-PROTECT
1783 ;; to be dropped.
1784 (release-foo foo))))
1786 might miss calling RELEASE-FOO despite GET-FOO having returned true if
1787 the interrupt occurs inside the cleanup clause, eg. during execution
1788 of RELEASE-FOO.
1790 Thus, in order to write an asynch unwind safe UNWIND-PROTECT you need
1791 to use WITHOUT-INTERRUPTS:
1793 (let (foo)
1794 (sb-sys:without-interrupts
1795 (unwind-protect
1796 (progn
1797 (setf foo (sb-sys:allow-with-interrupts
1798 (get-foo)))
1799 (sb-sys:with-local-interrupts
1800 (work-on-foo foo)))
1801 (when foo
1802 (release-foo foo)))))
1804 Since most libraries using UNWIND-PROTECT do not do this, you should never
1805 assume that unknown code can safely be terminated using TERMINATE-THREAD."
1806 (interrupt-thread thread (lambda () (abort-thread :allow-exit t))))
1808 (define-alien-routine "thread_yield" int)
1810 #!+sb-doc
1811 (setf (fdocumentation 'thread-yield 'function)
1812 "Yield the processor to other threads.")
1814 ;;; internal use only. If you think you need to use these, either you
1815 ;;; are an SBCL developer, are doing something that you should discuss
1816 ;;; with an SBCL developer first, or are doing something that you
1817 ;;; should probably discuss with a professional psychiatrist first
1818 #!+sb-thread
1819 (progn
1820 (defun %thread-sap (thread)
1821 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1822 (target (thread-os-thread thread)))
1823 (loop
1824 (when (sap= thread-sap (int-sap 0)) (return nil))
1825 (let ((os-thread (sap-ref-word thread-sap
1826 (* sb!vm:n-word-bytes
1827 sb!vm::thread-os-thread-slot))))
1828 (when (= os-thread target) (return thread-sap))
1829 (setf thread-sap
1830 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1831 sb!vm::thread-next-slot)))))))
1833 (defun %symbol-value-in-thread (symbol thread)
1834 ;; Prevent the thread from dying completely while we look for the TLS
1835 ;; area...
1836 (with-all-threads-lock
1837 (if (thread-alive-p thread)
1838 (let* ((offset (get-lisp-obj-address (symbol-tls-index symbol)))
1839 (obj (sap-ref-lispobj (%thread-sap thread) offset))
1840 (tl-val (get-lisp-obj-address obj)))
1841 (cond ((zerop offset)
1842 (values nil :no-tls-value))
1843 ((or (eql tl-val sb!vm:no-tls-value-marker-widetag)
1844 (eql tl-val sb!vm:unbound-marker-widetag))
1845 (values nil :unbound-in-thread))
1847 (values obj :ok))))
1848 (values nil :thread-dead))))
1850 (defun %set-symbol-value-in-thread (symbol thread value)
1851 (with-pinned-objects (value)
1852 ;; Prevent the thread from dying completely while we look for the TLS
1853 ;; area...
1854 (with-all-threads-lock
1855 (if (thread-alive-p thread)
1856 (let ((offset (get-lisp-obj-address (symbol-tls-index symbol))))
1857 (cond ((zerop offset)
1858 (values nil :no-tls-value))
1860 (setf (sap-ref-lispobj (%thread-sap thread) offset)
1861 value)
1862 (values value :ok))))
1863 (values nil :thread-dead)))))
1865 (define-alien-variable tls-index-start unsigned-int)
1867 ;; Get values from the TLS area of the current thread.
1868 (defun %thread-local-references ()
1869 ;; TLS-INDEX-START is a word number relative to thread base.
1870 ;; *FREE-TLS-INDEX* - which is only manipulated by machine code - is an
1871 ;; offset from thread base to the next usable TLS cell as a raw word
1872 ;; manifesting in Lisp as a fixnum. Convert it from byte number to word
1873 ;; number before using it as the upper bound for the sequential scan.
1874 (loop for index from tls-index-start
1875 ;; On x86-64, mask off the sign bit. It is used as a semaphore.
1876 below (ash (logand #!+x86-64 most-positive-fixnum
1877 sb!vm::*free-tls-index*)
1878 (+ (- sb!vm:word-shift) sb!vm:n-fixnum-tag-bits))
1879 for obj = (sb!kernel:%make-lisp-obj
1880 (sb!sys:sap-int (sb!vm::current-thread-offset-sap index)))
1881 unless (or (member (widetag-of obj)
1882 `(,sb!vm:no-tls-value-marker-widetag
1883 ,sb!vm:unbound-marker-widetag))
1884 (typep obj '(or fixnum character))
1885 (memq obj seen))
1886 collect obj into seen
1887 finally (return seen))))
1889 (defun symbol-value-in-thread (symbol thread &optional (errorp t))
1890 #!+sb-doc
1891 "Return the local value of SYMBOL in THREAD, and a secondary value of T
1892 on success.
1894 If the value cannot be retrieved (because the thread has exited or because it
1895 has no local binding for NAME) and ERRORP is true signals an error of type
1896 SYMBOL-VALUE-IN-THREAD-ERROR; if ERRORP is false returns a primary value of
1897 NIL, and a secondary value of NIL.
1899 Can also be used with SETF to change the thread-local value of SYMBOL.
1901 SYMBOL-VALUE-IN-THREAD is primarily intended as a debugging tool, and not as a
1902 mechanism for inter-thread communication."
1903 (declare (symbol symbol) (thread thread))
1904 #!+sb-thread
1905 (multiple-value-bind (res status) (%symbol-value-in-thread symbol thread)
1906 (if (eq :ok status)
1907 (values res t)
1908 (if errorp
1909 (error 'symbol-value-in-thread-error
1910 :name symbol
1911 :thread thread
1912 :info (list :read status))
1913 (values nil nil))))
1914 #!-sb-thread
1915 (if (boundp symbol)
1916 (values (symbol-value symbol) t)
1917 (if errorp
1918 (error 'symbol-value-in-thread-error
1919 :name symbol
1920 :thread thread
1921 :info (list :read :unbound-in-thread))
1922 (values nil nil))))
1924 (defun (setf symbol-value-in-thread) (value symbol thread &optional (errorp t))
1925 (declare (symbol symbol) (thread thread))
1926 #!+sb-thread
1927 (multiple-value-bind (res status) (%set-symbol-value-in-thread symbol thread value)
1928 (if (eq :ok status)
1929 (values res t)
1930 (if errorp
1931 (error 'symbol-value-in-thread-error
1932 :name symbol
1933 :thread thread
1934 :info (list :write status))
1935 (values nil nil))))
1936 #!-sb-thread
1937 (if (boundp symbol)
1938 (values (setf (symbol-value symbol) value) t)
1939 (if errorp
1940 (error 'symbol-value-in-thread-error
1941 :name symbol
1942 :thread thread
1943 :info (list :write :unbound-in-thread))
1944 (values nil nil))))
1948 ;;;; Stepping
1950 (defun thread-stepping ()
1951 (sap-ref-lispobj (current-thread-sap)
1952 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes)))
1954 (defun (setf thread-stepping) (value)
1955 (setf (sap-ref-lispobj (current-thread-sap)
1956 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1957 value))