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")
14 ;;; Of the WITH-PINNED-OBJECTS in this file, not every single one is
15 ;;; necessary because threads are only supported with the conservative
16 ;;; gencgc and numbers on the stack (returned by GET-LISP-OBJ-ADDRESS)
17 ;;; are treated as references.
19 ;;; set the doc here because in early-thread FDOCUMENTATION is not
22 (setf (fdocumentation '*current-thread
* 'variable
)
23 "Bound in each thread to the thread itself.")
25 (defstruct (thread (:constructor %make-thread
))
27 "Thread type. Do not rely on threads being structs as it may change
33 (interruptions-lock (make-mutex :name
"thread interruptions lock"))
35 (result-lock (make-mutex :name
"thread result lock")))
38 (setf (fdocumentation 'thread-name
'function
)
39 "The name of the thread. Setfable.")
41 (def!method print-object
((thread thread
) stream
)
42 (print-unreadable-object (thread stream
:type t
:identity t
)
43 (let* ((cookie (list thread
))
44 (info (if (thread-alive-p thread
)
47 (join-thread thread
:default cookie
))))
48 (state (if (eq :running info
)
50 (if (eq cookie
(car info
))
53 (values (when (eq :finished state
) info
)))
55 "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
61 (defun thread-alive-p (thread)
63 "Check if THREAD is running."
64 (thread-%alive-p thread
))
66 ;; A thread is eligible for gc iff it has finished and there are no
67 ;; more references to it. This list is supposed to keep a reference to
68 ;; all running threads.
69 (defvar *all-threads
* ())
70 (defvar *all-threads-lock
* (make-mutex :name
"all threads lock"))
72 (defvar *default-alloc-signal
* nil
)
74 (defmacro with-all-threads-lock
(&body body
)
75 `(with-system-mutex (*all-threads-lock
*)
78 (defun list-all-threads ()
80 "Return a list of the live threads."
81 (with-all-threads-lock
82 (copy-list *all-threads
*)))
84 (declaim (inline current-thread-sap
))
85 (defun current-thread-sap ()
86 (sb!vm
::current-thread-offset-sap sb
!vm
::thread-this-slot
))
88 (declaim (inline current-thread-os-thread
))
89 (defun current-thread-os-thread ()
91 (sap-int (sb!vm
::current-thread-offset-sap sb
!vm
::thread-os-thread-slot
))
95 (defun init-initial-thread ()
96 (/show0
"Entering INIT-INITIAL-THREAD")
97 (let ((initial-thread (%make-thread
:name
"initial thread"
99 :os-thread
(current-thread-os-thread))))
100 (setq *current-thread
* initial-thread
)
101 ;; Either *all-threads* is empty or it contains exactly one thread
102 ;; in case we are in reinit since saving core with multiple
103 ;; threads doesn't work.
104 (setq *all-threads
* (list initial-thread
))))
107 ;;;; Aliens, low level stuff
109 (define-alien-routine "kill_safely"
111 (os-thread #!-alpha unsigned-long
#!+alpha unsigned-int
)
116 ;; FIXME it would be good to define what a thread id is or isn't
117 ;; (our current assumption is that it's a fixnum). It so happens
118 ;; that on Linux it's a pid, but it might not be on posix thread
120 (define-alien-routine ("create_thread" %create-thread
)
121 unsigned-long
(lisp-fun-address unsigned-long
))
123 (declaim (inline %block-deferrable-signals
))
124 (define-alien-routine ("block_deferrable_signals" %block-deferrable-signals
)
126 (where sb
!alien
:unsigned-long
)
127 (old sb
!alien
:unsigned-long
))
129 (defun block-deferrable-signals ()
130 (%block-deferrable-signals
0 0))
134 (declaim (inline %lutex-init %lutex-wait %lutex-wake
135 %lutex-lock %lutex-unlock
))
137 (define-alien-routine ("lutex_init" %lutex-init
)
138 int
(lutex unsigned-long
))
140 (define-alien-routine ("lutex_wait" %lutex-wait
)
141 int
(queue-lutex unsigned-long
) (mutex-lutex unsigned-long
))
143 (define-alien-routine ("lutex_wake" %lutex-wake
)
144 int
(lutex unsigned-long
) (n int
))
146 (define-alien-routine ("lutex_lock" %lutex-lock
)
147 int
(lutex unsigned-long
))
149 (define-alien-routine ("lutex_trylock" %lutex-trylock
)
150 int
(lutex unsigned-long
))
152 (define-alien-routine ("lutex_unlock" %lutex-unlock
)
153 int
(lutex unsigned-long
))
155 (define-alien-routine ("lutex_destroy" %lutex-destroy
)
156 int
(lutex unsigned-long
))
158 ;; FIXME: Defining a whole bunch of alien-type machinery just for
159 ;; passing primitive lutex objects directly to foreign functions
160 ;; doesn't seem like fun right now. So instead we just manually
161 ;; pin the lutex, get its address, and let the callee untag it.
162 (defmacro with-lutex-address
((name lutex
) &body body
)
163 `(let ((,name
,lutex
))
164 (with-pinned-objects (,name
)
165 (let ((,name
(get-lisp-obj-address ,name
)))
169 (/show0
"Entering MAKE-LUTEX")
170 ;; Suppress GC until the lutex has been properly registered with
173 (let ((lutex (sb!vm
::%make-lutex
)))
176 (with-lutex-address (lutex lutex
)
182 (declaim (inline futex-wait %futex-wait futex-wake
))
184 (define-alien-routine ("futex_wait" %futex-wait
)
185 int
(word unsigned-long
) (old-value unsigned-long
)
186 (to-sec long
) (to-usec unsigned-long
))
188 (defun futex-wait (word old to-sec to-usec
)
190 (%futex-wait word old to-sec to-usec
)))
192 (define-alien-routine "futex_wake"
193 int
(word unsigned-long
) (n unsigned-long
))))
195 ;;; used by debug-int.lisp to access interrupt contexts
196 #!-
(or sb-fluid sb-thread
) (declaim (inline sb
!vm
::current-thread-offset-sap
))
198 (defun sb!vm
::current-thread-offset-sap
(n)
199 (declare (type (unsigned-byte 27) n
))
200 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t
)))
201 (* n sb
!vm
:n-word-bytes
)))
204 (defun sb!vm
::current-thread-offset-sap
(n)
205 (declare (type (unsigned-byte 27) n
))
206 (sb!vm
::current-thread-offset-sap n
))
211 (declaim (inline get-spinlock release-spinlock
))
213 ;;; Should always be called with interrupts disabled.
214 (defun get-spinlock (spinlock)
215 (declare (optimize (speed 3) (safety 0)))
216 (let* ((new *current-thread
*)
217 (old (sb!ext
:compare-and-swap
(spinlock-value spinlock
) nil new
)))
220 (error "Recursive lock attempt on ~S." spinlock
))
223 (if (sb!ext
:compare-and-swap
(spinlock-value spinlock
) nil new
)
225 (return-from get-spinlock t
))))
226 (if (and (not *interrupts-enabled
*) *allow-with-interrupts
*)
227 ;; If interrupts are disabled, but we are allowed to
228 ;; enabled them, check for pending interrupts every once
229 ;; in a while. %CHECK-INTERRUPTS is taking shortcuts, make
230 ;; sure that deferrables are unblocked by doing an empty
231 ;; WITH-INTERRUPTS once.
235 (loop repeat
128 do
(cas)) ; 128 is arbitrary here
236 (sb!unix
::%check-interrupts
)))
240 (defun release-spinlock (spinlock)
241 (declare (optimize (speed 3) (safety 0)))
242 ;; On x86 and x86-64 we can get away with no memory barriers, (see
243 ;; Linux kernel mailing list "spin_unlock optimization(i386)"
244 ;; thread, summary at
245 ;; http://kt.iserv.nl/kernel-traffic/kt19991220_47.html#1.
247 ;; If the compiler may reorder this with other instructions, insert
248 ;; compiler barrier here.
250 ;; FIXME: this does not work on SMP Pentium Pro and OOSTORE systems,
251 ;; neither on most non-x86 architectures (but we don't have threads
253 (setf (spinlock-value spinlock
) nil
))
259 (setf (fdocumentation 'make-mutex
'function
)
261 (fdocumentation 'mutex-name
'function
)
262 "The name of the mutex. Setfable.")
264 #!+(and sb-thread
(not sb-lutex
))
266 (define-structure-slot-addressor mutex-state-address
269 ;; Important: current code assumes these are fixnums or other
270 ;; lisp objects that don't need pinning.
271 (defconstant +lock-free
+ 0)
272 (defconstant +lock-taken
+ 1)
273 (defconstant +lock-contested
+ 2))
275 (defun mutex-owner (mutex)
276 "Current owner of the mutex, NIL if the mutex is free. Naturally,
277 this is racy by design (another thread may acquire the mutex after
278 this function returns), it is intended for informative purposes. For
279 testing whether the current thread is holding a mutex see
281 ;; Make sure to get the current value.
282 (sb!ext
:compare-and-swap
(mutex-%owner mutex
) nil nil
))
284 (defun get-mutex (mutex &optional
(new-owner *current-thread
*) (waitp t
))
286 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
287 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
288 non-NIL and the mutex is in use, sleep until it is available.
290 Note: using GET-MUTEX to assign a MUTEX to another thread then the
291 current one is not recommended, and liable to be deprecated.
293 GET-MUTEX is not interrupt safe. The correct way to call it is:
297 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
300 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
301 call while the mutex is in an inconsistent state while
302 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
304 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
306 (declare (type mutex mutex
) (optimize (speed 3))
307 #!-sb-thread
(ignore waitp
))
309 (setq new-owner
*current-thread
*))
310 (let ((old (mutex-%owner mutex
)))
311 (when (eq new-owner old
)
312 (error "Recursive lock attempt ~S." mutex
))
315 (error "Strange deadlock on ~S in an unithreaded build?" mutex
)))
317 (setf (mutex-%owner mutex
) new-owner
)
320 ;; FIXME: Lutexes do not currently support deadlines, as at least
321 ;; on Darwin pthread_foo_timedbar functions are not supported:
322 ;; this means that we probably need to use the Carbon multiprocessing
323 ;; functions on Darwin.
325 ;; FIXME: This is definitely not interrupt safe: what happens if
326 ;; we get hit (1) during the lutex calls (ok, they may be safe,
327 ;; but has that been checked?) (2) after the lutex call, but
328 ;; before setting the mutex owner.
330 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex
))
332 (with-interrupts (%lutex-lock lutex
))
333 (%lutex-trylock lutex
))))
334 (setf (mutex-%owner mutex
) new-owner
)
337 ;; This is a direct translation of the Mutex 2 algorithm from
338 ;; "Futexes are Tricky" by Ulrich Drepper.
339 (let ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
342 (unless (or (eql +lock-free
+ old
) (not waitp
))
345 (when (or (eql +lock-contested
+ old
)
346 (not (eql +lock-free
+
347 (sb!ext
:compare-and-swap
(mutex-state mutex
)
350 ;; Wait on the contested lock.
352 (multiple-value-bind (to-sec to-usec
) (decode-timeout nil
)
353 (case (with-pinned-objects (mutex)
354 (futex-wait (mutex-state-address mutex
)
355 (get-lisp-obj-address +lock-contested
+)
358 ((1) (signal-deadline))
360 (otherwise (return))))))
361 (setf old
(sb!ext
:compare-and-swap
(mutex-state mutex
)
365 (unless (eql +lock-free
+ old
)
367 (cond ((eql +lock-free
+ old
)
368 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
)
371 (bug "Old owner in free mutex: ~S" prev
))
374 (bug "Failed to acquire lock with WAITP."))))))
376 (defun release-mutex (mutex &key
(if-not-owner :punt
))
378 "Release MUTEX by setting it to NIL. Wake up threads waiting for
381 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
384 If the current thread is not the owner of the mutex then it silently
385 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
386 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
387 IF-NOT-OWNER is :FORCE)."
388 (declare (type mutex mutex
))
389 ;; Order matters: set owner to NIL before releasing state.
390 (let* ((self *current-thread
*)
391 (old-owner (sb!ext
:compare-and-swap
(mutex-%owner mutex
) self nil
)))
392 (unless (eql self old-owner
)
394 ((:punt
) (return-from release-mutex nil
))
396 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner
))
400 (setf (mutex-%owner mutex
) nil
)
402 (with-lutex-address (lutex (mutex-lutex mutex
))
403 (%lutex-unlock lutex
))
405 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
406 ;; unsigned-byte type this can be used:
408 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
409 ;; (unless (eql old +lock-free+)
410 ;; (setf (mutex-state mutex) +lock-free+)
411 ;; (with-pinned-objects (mutex)
412 ;; (futex-wake (mutex-state-address mutex) 1))))
413 (let ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
414 +lock-taken
+ +lock-free
+)))
415 (when (eql old
+lock-contested
+)
416 (sb!ext
:compare-and-swap
(mutex-state mutex
)
417 +lock-contested
+ +lock-free
+)
418 (with-pinned-objects (mutex)
419 (futex-wake (mutex-state-address mutex
) 1))))
423 ;;;; Waitqueues/condition variables
425 (defstruct (waitqueue (:constructor %make-waitqueue
))
428 (name nil
:type
(or null simple-string
))
429 #!+(and sb-lutex sb-thread
)
434 (defun make-waitqueue (&key name
)
436 "Create a waitqueue."
437 (%make-waitqueue
:name name
))
440 (setf (fdocumentation 'waitqueue-name
'function
)
441 "The name of the waitqueue. Setfable.")
443 #!+(and sb-thread
(not sb-lutex
))
444 (define-structure-slot-addressor waitqueue-data-address
448 (defun condition-wait (queue mutex
)
450 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
451 thread may subsequently notify us using CONDITION-NOTIFY, at which
452 time we reacquire MUTEX and return to the caller."
453 #!-sb-thread
(declare (ignore queue
))
455 #!-sb-thread
(error "Not supported in unithread builds.")
457 (let ((me *current-thread
*))
458 (assert (eq me
(mutex-%owner mutex
)))
459 (/show0
"CONDITION-WAITing")
461 ;; Need to disable interrupts so that we don't miss setting the
462 ;; owner on our way out. (pthread_cond_wait handles the actual
467 (setf (mutex-%owner mutex
) nil
)
468 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue
))
469 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex
))
470 (with-local-interrupts
471 (%lutex-wait queue-lutex-address mutex-lutex-address
)))))
472 (setf (mutex-%owner mutex
) me
)))
474 ;; Need to disable interrupts so that we don't miss grabbing the
475 ;; mutex on our way out.
478 ;; This setf becomes visible to other CPUS due to the usual
479 ;; memory barrier semantics of lock acquire/release. This must
480 ;; not be moved into the loop else wakeups may be lost upon
481 ;; continuing after a deadline or EINTR.
482 (setf (waitqueue-data queue
) me
)
484 (multiple-value-bind (to-sec to-usec
) (decode-timeout nil
)
485 (case (unwind-protect
486 (with-pinned-objects (queue me
)
487 ;; RELEASE-MUTEX is purposefully as close to
488 ;; FUTEX-WAIT as possible to reduce the size
489 ;; of the window where WAITQUEUE-DATA may be
490 ;; set by a notifier.
491 (release-mutex mutex
)
492 ;; Now we go to sleep using futex-wait. If
493 ;; anyone else manages to grab MUTEX and call
494 ;; CONDITION-NOTIFY during this comment, it
495 ;; will change queue->data, and so futex-wait
496 ;; returns immediately instead of sleeping.
497 ;; Ergo, no lost wakeup. We may get spurious
498 ;; wakeups, but that's ok.
499 (allow-with-interrupts
500 (futex-wait (waitqueue-data-address queue
)
501 (get-lisp-obj-address me
)
502 ;; our way if saying "no
506 ;; If we are interrupted while waiting, we should
507 ;; do these things before returning. Ideally, in
508 ;; the case of an unhandled signal, we should do
509 ;; them before entering the debugger, but this is
510 ;; better than nothing.
511 (allow-with-interrupts (get-mutex mutex
)))
513 ((1) (signal-deadline))
516 ;; EWOULDBLOCK, -1 here, is the possible spurious wakeup
517 ;; case. 0 is the normal wakeup.
518 (otherwise (return)))))))))
520 (defun condition-notify (queue &optional
(n 1))
522 "Notify N threads waiting on QUEUE. The same mutex that is used in
523 the corresponding CONDITION-WAIT must be held by this thread during
525 #!-sb-thread
(declare (ignore queue n
))
526 #!-sb-thread
(error "Not supported in unithread builds.")
528 (declare (type (and fixnum
(integer 1)) n
))
529 (/show0
"Entering CONDITION-NOTIFY")
533 (with-lutex-address (lutex (waitqueue-lutex queue
))
534 (%lutex-wake lutex n
))
535 ;; no problem if >1 thread notifies during the comment in
536 ;; condition-wait: as long as the value in queue-data isn't the
537 ;; waiting thread's id, it matters not what it is
538 ;; XXX we should do something to ensure that the result of this setf
539 ;; is visible to all CPUs
541 (let ((me *current-thread
*))
543 (setf (waitqueue-data queue
) me
)
544 (with-pinned-objects (queue)
545 (futex-wake (waitqueue-data-address queue
) n
))))))
547 (defun condition-broadcast (queue)
549 "Notify all threads waiting on QUEUE."
550 (condition-notify queue
551 ;; On a 64-bit platform truncating M-P-F to an int
552 ;; results in -1, which wakes up only one thread.
554 most-positive-fixnum
)))
559 (defstruct (semaphore (:constructor %make-semaphore
(name %count
)))
561 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
562 should be considered an implementation detail, and may change in the
564 (name nil
:type
(or null simple-string
))
565 (%count
0 :type
(integer 0))
566 (waitcount 0 :type
(integer 0))
568 (queue (make-waitqueue)))
570 (setf (fdocumentation 'semaphore-name
'function
)
571 "The name of the semaphore INSTANCE. Setfable.")
573 (declaim (inline semaphore-count
))
574 (defun semaphore-count (instance)
575 "Returns the current count of the semaphore INSTANCE."
576 (semaphore-%count instance
))
578 (defun make-semaphore (&key name
(count 0))
580 "Create a semaphore with the supplied COUNT and NAME."
581 (%make-semaphore name count
))
583 (defun wait-on-semaphore (semaphore)
585 "Decrement the count of SEMAPHORE if the count would not be
586 negative. Else blocks until the semaphore can be decremented."
587 ;; A more direct implementation based directly on futexes should be
590 ;; We need to disable interrupts so that we don't forget to
591 ;; decrement the waitcount (which would happen if an asynch
592 ;; interrupt should catch us on our way out from the loop.)
593 (with-system-mutex ((semaphore-mutex semaphore
) :allow-with-interrupts t
)
594 ;; Quick check: is it positive? If not, enter the wait loop.
595 (let ((count (semaphore-%count semaphore
)))
597 (setf (semaphore-%count semaphore
) (1- count
))
600 (incf (semaphore-waitcount semaphore
))
601 (loop until
(plusp (setf count
(semaphore-%count semaphore
)))
602 do
(condition-wait (semaphore-queue semaphore
)
603 (semaphore-mutex semaphore
)))
604 (setf (semaphore-%count semaphore
) (1- count
)))
605 (decf (semaphore-waitcount semaphore
)))))))
607 (defun signal-semaphore (semaphore &optional
(n 1))
609 "Increment the count of SEMAPHORE by N. If there are threads waiting
610 on this semaphore, then N of them is woken up."
611 (declare (type (integer 1) n
))
612 ;; Need to disable interrupts so that we don't lose a wakeup after
613 ;; we have incremented the count.
614 (with-system-mutex ((semaphore-mutex semaphore
))
615 (let ((waitcount (semaphore-waitcount semaphore
))
616 (count (incf (semaphore-%count semaphore
) n
)))
617 (when (plusp waitcount
)
618 (condition-notify (semaphore-queue semaphore
) (min waitcount count
))))))
621 ;;;; Job control, independent listeners
624 (lock (make-mutex :name
"session lock"))
626 (interactive-threads nil
)
627 (interactive-threads-queue (make-waitqueue)))
629 (defvar *session
* nil
)
631 ;;; The debugger itself tries to acquire the session lock, don't let
632 ;;; funny situations (like getting a sigint while holding the session
633 ;;; lock) occur. At the same time we need to allow interrupts while
634 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
635 ;;; be interruptible.
637 ;;; Take care: we sometimes need to obtain the session lock while
638 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
639 ;;; _after_ getting a session lock! (Deadlock risk.)
641 ;;; FIXME: It would be good to have ordered locks to ensure invariants
643 (defmacro with-session-lock
((session) &body body
)
644 `(with-system-mutex ((session-lock ,session
) :allow-with-interrupts t
)
647 (defun new-session ()
648 (make-session :threads
(list *current-thread
*)
649 :interactive-threads
(list *current-thread
*)))
651 (defun init-job-control ()
652 (/show0
"Entering INIT-JOB-CONTROL")
653 (setf *session
* (new-session))
654 (/show0
"Exiting INIT-JOB-CONTROL"))
656 (defun %delete-thread-from-session
(thread session
)
657 (with-session-lock (session)
658 (setf (session-threads session
)
659 (delete thread
(session-threads session
))
660 (session-interactive-threads session
)
661 (delete thread
(session-interactive-threads session
)))))
663 (defun call-with-new-session (fn)
664 (%delete-thread-from-session
*current-thread
* *session
*)
665 (let ((*session
* (new-session)))
668 (defmacro with-new-session
(args &body forms
)
669 (declare (ignore args
)) ;for extensibility
670 (sb!int
:with-unique-names
(fb-name)
671 `(labels ((,fb-name
() ,@forms
))
672 (call-with-new-session (function ,fb-name
)))))
674 ;;; Remove thread from its session, if it has one.
676 (defun handle-thread-exit (thread)
677 (/show0
"HANDLING THREAD EXIT")
679 (with-all-threads-lock
680 (setf (thread-%alive-p thread
) nil
)
681 (setf (thread-os-thread thread
) nil
)
682 (setq *all-threads
* (delete thread
*all-threads
*))
684 (%delete-thread-from-session thread
*session
*)))
687 (/show0
"FREEING MUTEX LUTEX")
688 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread
)))
689 (%lutex-destroy lutex
))))
691 (defun terminate-session ()
693 "Kill all threads in session except for this one. Does nothing if current
694 thread is not the foreground thread."
695 ;; FIXME: threads created in other threads may escape termination
697 (with-session-lock (*session
*)
698 (and (eq *current-thread
*
699 (car (session-interactive-threads *session
*)))
700 (session-threads *session
*)))))
701 ;; do the kill after dropping the mutex; unwind forms in dying
702 ;; threads may want to do session things
703 (dolist (thread to-kill
)
704 (unless (eq thread
*current-thread
*)
705 ;; terminate the thread but don't be surprised if it has
706 ;; exited in the meantime
707 (handler-case (terminate-thread thread
)
708 (interrupt-thread-error ()))))))
710 ;;; called from top of invoke-debugger
711 (defun debugger-wait-until-foreground-thread (stream)
712 "Returns T if thread had been running in background, NIL if it was
714 (declare (ignore stream
))
718 (with-session-lock (*session
*)
719 (not (member *current-thread
*
720 (session-interactive-threads *session
*))))
723 (defun get-foreground ()
726 (let ((was-foreground t
))
728 (/show0
"Looping in GET-FOREGROUND")
729 (with-session-lock (*session
*)
730 (let ((int-t (session-interactive-threads *session
*)))
731 (when (eq (car int-t
) *current-thread
*)
732 (unless was-foreground
733 (format *query-io
* "Resuming thread ~A~%" *current-thread
*))
734 (return-from get-foreground t
))
735 (setf was-foreground nil
)
736 (unless (member *current-thread
* int-t
)
737 (setf (cdr (last int-t
))
738 (list *current-thread
*)))
740 (session-interactive-threads-queue *session
*)
741 (session-lock *session
*)))))))
743 (defun release-foreground (&optional next
)
745 "Background this thread. If NEXT is supplied, arrange for it to
746 have the foreground next."
747 #!-sb-thread
(declare (ignore next
))
750 (with-session-lock (*session
*)
751 (when (rest (session-interactive-threads *session
*))
752 (setf (session-interactive-threads *session
*)
753 (delete *current-thread
* (session-interactive-threads *session
*))))
755 (setf (session-interactive-threads *session
*)
757 (delete next
(session-interactive-threads *session
*)))))
758 (condition-broadcast (session-interactive-threads-queue *session
*))))
760 (defun foreground-thread ()
761 (car (session-interactive-threads *session
*)))
763 (defun make-listener-thread (tty-name)
764 (assert (probe-file tty-name
))
765 (let* ((in (sb!unix
:unix-open
(namestring tty-name
) sb
!unix
:o_rdwr
#o666
))
766 (out (sb!unix
:unix-dup in
))
767 (err (sb!unix
:unix-dup in
)))
768 (labels ((thread-repl ()
769 (sb!unix
::unix-setsid
)
770 (let* ((sb!impl
::*stdin
*
771 (make-fd-stream in
:input t
:buffering
:line
774 (make-fd-stream out
:output t
:buffering
:line
777 (make-fd-stream err
:output t
:buffering
:line
780 (make-fd-stream err
:input t
:output t
783 (sb!impl
::*descriptor-handlers
* nil
))
786 (sb!impl
::toplevel-repl nil
)
787 (sb!int
:flush-standard-output-streams
))))))
788 (make-thread #'thread-repl
))))
793 (defun make-thread (function &key name
)
795 "Create a new thread of NAME that runs FUNCTION. When the function
796 returns the thread exits. The return values of FUNCTION are kept
797 around and can be retrieved by JOIN-THREAD."
798 #!-sb-thread
(declare (ignore function name
))
799 #!-sb-thread
(error "Not supported in unithread builds.")
801 (let* ((thread (%make-thread
:name name
))
802 (setup-sem (make-semaphore :name
"Thread setup semaphore"))
803 (real-function (coerce function
'function
))
806 ;; In time we'll move some of the binding presently done in C
809 ;; KLUDGE: Here we have a magic list of variables that are
810 ;; not thread-safe for one reason or another. As people
811 ;; report problems with the thread safety of certain
812 ;; variables, (e.g. "*print-case* in multiple threads
813 ;; broken", sbcl-devel 2006-07-14), we add a few more
814 ;; bindings here. The Right Thing is probably some variant
815 ;; of Allegro's *cl-default-special-bindings*, as that is at
816 ;; least accessible to users to secure their own libraries.
819 ;; As it is, this lambda must not cons until we are ready
820 ;; to run GC. Be very careful.
821 (let* ((*current-thread
* thread
)
822 (*restart-clusters
* nil
)
823 (*handler-clusters
* (sb!kernel
::initial-handler-clusters
))
824 (*condition-restarts
* nil
)
825 (sb!impl
::*deadline
* nil
)
826 (sb!impl
::*step-out
* nil
)
827 ;; internal printer variables
828 (sb!impl
::*previous-case
* nil
)
829 (sb!impl
::*previous-readtable-case
* nil
)
831 (sb!impl
::*merge-sort-temp-vector
* empty
)
832 (sb!impl
::*zap-array-data-temp
* empty
)
833 (sb!impl
::*internal-symbol-output-fun
* nil
)
834 (sb!impl
::*descriptor-handlers
* nil
)) ; serve-event
836 (setf sb
!vm
:*alloc-signal
* *default-alloc-signal
*)
837 (setf (thread-os-thread thread
) (current-thread-os-thread))
838 (with-mutex ((thread-result-lock thread
))
839 (with-all-threads-lock
840 (push thread
*all-threads
*))
841 (with-session-lock (*session
*)
842 (push thread
(session-threads *session
*)))
843 (setf (thread-%alive-p thread
) t
)
844 (signal-semaphore setup-sem
)
845 ;; can't use handling-end-of-the-world, because that flushes
846 ;; output streams, and we don't necessarily have any (or we
847 ;; could be sharing them)
848 (catch 'sb
!impl
::toplevel-catcher
849 (catch 'sb
!impl
::%end-of-the-world
853 "~~@<Terminate this thread (~A)~~@:>"
857 (with-local-interrupts
858 ;; Now that most things have a chance
859 ;; to work properly without messing up
860 ;; other threads, it's time to enable
862 (sb!unix
::unblock-deferrable-signals
)
863 (setf (thread-result thread
)
866 (funcall real-function
))))
867 ;; Try to block deferrables. An
868 ;; interrupt may unwind it, but for a
869 ;; normal exit it prevents interrupt
871 (block-deferrable-signals))
872 ;; We're going down, can't handle interrupts
873 ;; sanely anymore. GC remains enabled.
874 (block-deferrable-signals)
875 ;; We don't want to run interrupts in a dead
876 ;; thread when we leave WITHOUT-INTERRUPTS.
877 ;; This potentially causes important
878 ;; interupts to be lost: SIGINT comes to
880 (setq *interrupt-pending
* nil
)
881 (handle-thread-exit thread
))))))))
883 ;; If the starting thread is stopped for gc before it signals the
884 ;; semaphore then we'd be stuck.
885 (assert (not *gc-inhibit
*))
886 ;; Keep INITIAL-FUNCTION pinned until the child thread is
887 ;; initialized properly. Wrap the whole thing in
888 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
891 (with-pinned-objects (initial-function)
894 (get-lisp-obj-address initial-function
))))
895 (when (zerop os-thread
)
896 (error "Can't create a new thread"))
897 (wait-on-semaphore setup-sem
)
900 (define-condition join-thread-error
(error)
901 ((thread :reader join-thread-error-thread
:initarg
:thread
))
903 (:documentation
"Joining thread failed.")
904 (:report
(lambda (c s
)
905 (format s
"Joining thread failed: thread ~A ~
906 has not returned normally."
907 (join-thread-error-thread c
)))))
910 (setf (fdocumentation 'join-thread-error-thread
'function
)
911 "The thread that we failed to join.")
913 (defun join-thread (thread &key
(default nil defaultp
))
915 "Suspend current thread until THREAD exits. Returns the result
916 values of the thread function. If the thread does not exit normally,
917 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
918 (with-system-mutex ((thread-result-lock thread
) :allow-with-interrupts t
)
919 (cond ((car (thread-result thread
))
920 (return-from join-thread
921 (values-list (cdr (thread-result thread
)))))
923 (return-from join-thread default
))))
924 (error 'join-thread-error
:thread thread
))
926 (defun destroy-thread (thread)
928 "Deprecated. Same as TERMINATE-THREAD."
929 (terminate-thread thread
))
931 (define-condition interrupt-thread-error
(error)
932 ((thread :reader interrupt-thread-error-thread
:initarg
:thread
))
934 (:documentation
"Interrupting thread failed.")
935 (:report
(lambda (c s
)
936 (format s
"Interrupt thread failed: thread ~A has exited."
937 (interrupt-thread-error-thread c
)))))
940 (setf (fdocumentation 'interrupt-thread-error-thread
'function
)
941 "The thread that was not interrupted.")
943 (defmacro with-interruptions-lock
((thread) &body body
)
944 `(with-system-mutex ((thread-interruptions-lock ,thread
))
947 ;;; Called from the signal handler.
949 (defun run-interruption ()
950 (let ((interruption (with-interruptions-lock (*current-thread
*)
951 (pop (thread-interruptions *current-thread
*)))))
952 ;; If there is more to do, then resignal and let the normal
953 ;; interrupt deferral mechanism take care of the rest. From the
954 ;; OS's point of view the signal we are in the handler for is no
955 ;; longer pending, so the signal will not be lost.
956 (when (thread-interruptions *current-thread
*)
957 (kill-safely (thread-os-thread *current-thread
*) sb
!unix
:sigpipe
))
959 (funcall interruption
))))
961 (defun interrupt-thread (thread function
)
963 "Interrupt the live THREAD and make it run FUNCTION. A moderate
964 degree of care is expected for use of INTERRUPT-THREAD, due to its
965 nature: if you interrupt a thread that was holding important locks
966 then do something that turns out to need those locks, you probably
967 won't like the effect. FUNCTION runs with interrupts disabled, but
968 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
969 enable interrupts (GET-MUTEX when contended, for instance) so the
970 first thing to do is usually a WITH-INTERRUPTS or a
971 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
972 run in same the order they were sent."
974 (declare (ignore thread
))
976 (with-interrupt-bindings
977 (with-interrupts (funcall function
)))
979 (let ((os-thread (thread-os-thread thread
)))
980 (cond ((not os-thread
)
981 (error 'interrupt-thread-error
:thread thread
))
983 (with-interruptions-lock (thread)
984 ;; Append to the end of the interruptions queue. It's
985 ;; O(N), but it does not hurt to slow interruptors down a
986 ;; bit when the queue gets long.
987 (setf (thread-interruptions thread
)
988 (append (thread-interruptions thread
)
991 (allow-with-interrupts
992 (funcall function
))))))))
993 (when (minusp (kill-safely os-thread sb
!unix
:sigpipe
))
994 (error 'interrupt-thread-error
:thread thread
))))))
996 (defun terminate-thread (thread)
998 "Terminate the thread identified by THREAD, by causing it to run
999 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
1000 (interrupt-thread thread
'sb
!ext
:quit
))
1002 (define-alien-routine "thread_yield" int
)
1005 (setf (fdocumentation 'thread-yield
'function
)
1006 "Yield the processor to other threads.")
1008 ;;; internal use only. If you think you need to use these, either you
1009 ;;; are an SBCL developer, are doing something that you should discuss
1010 ;;; with an SBCL developer first, or are doing something that you
1011 ;;; should probably discuss with a professional psychiatrist first
1014 (defun %thread-sap
(thread)
1015 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t
))))
1016 (target (thread-os-thread thread
)))
1018 (when (sap= thread-sap
(int-sap 0)) (return nil
))
1019 (let ((os-thread (sap-ref-word thread-sap
1020 (* sb
!vm
:n-word-bytes
1021 sb
!vm
::thread-os-thread-slot
))))
1022 (when (= os-thread target
) (return thread-sap
))
1024 (sap-ref-sap thread-sap
(* sb
!vm
:n-word-bytes
1025 sb
!vm
::thread-next-slot
)))))))
1027 (defun %symbol-value-in-thread
(symbol thread
)
1029 ;; Prevent the dead from dying completely while we look for the
1031 (with-all-threads-lock
1032 (if (thread-alive-p thread
)
1033 (let* ((offset (* sb
!vm
:n-word-bytes
1034 (sb!vm
::symbol-tls-index symbol
)))
1035 (tl-val (sap-ref-word (%thread-sap thread
) offset
)))
1036 (if (eql tl-val sb
!vm
::no-tls-value-marker-widetag
)
1038 (return-from %symbol-value-in-thread
1039 (values (make-lisp-obj tl-val
) t
))))
1040 (return-from %symbol-value-in-thread
(values nil nil
))))
1042 (error "Cannot read thread-local symbol value: ~S unbound in ~S"
1045 (defun %set-symbol-value-in-thread
(symbol thread value
)
1047 (with-pinned-objects (value)
1048 ;; Prevent the dead from dying completely while we look for
1050 (with-all-threads-lock
1051 (if (thread-alive-p thread
)
1052 (let* ((offset (* sb
!vm
:n-word-bytes
1053 (sb!vm
::symbol-tls-index symbol
)))
1054 (sap (%thread-sap thread
))
1055 (tl-val (sap-ref-word sap offset
)))
1056 (if (eql tl-val sb
!vm
::no-tls-value-marker-widetag
)
1058 (setf (sap-ref-word sap offset
)
1059 (get-lisp-obj-address value
)))
1060 (return-from %set-symbol-value-in-thread
(values value t
)))
1061 (return-from %set-symbol-value-in-thread
(values nil nil
)))))
1063 (error "Cannot set thread-local symbol value: ~S unbound in ~S"
1066 (defun sb!vm
::locked-symbol-global-value-add
(symbol-name delta
)
1067 (sb!vm
::locked-symbol-global-value-add symbol-name delta
))
1072 (defun thread-stepping ()
1074 (sap-ref-word (current-thread-sap)
1075 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
))))
1077 (defun (setf thread-stepping
) (value)
1078 (setf (sap-ref-word (current-thread-sap)
1079 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
))
1080 (get-lisp-obj-address value
)))