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 (define-alien-routine "block_deferrable_signals"
128 (declaim (inline %lutex-init %lutex-wait %lutex-wake
129 %lutex-lock %lutex-unlock))
131 (define-alien-routine ("lutex_init" %lutex-init)
132 int (lutex unsigned-long))
134 (define-alien-routine ("lutex_wait" %lutex-wait)
135 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
137 (define-alien-routine ("lutex_wake" %lutex-wake)
138 int (lutex unsigned-long) (n int))
140 (define-alien-routine ("lutex_lock" %lutex-lock)
141 int (lutex unsigned-long))
143 (define-alien-routine ("lutex_trylock" %lutex-trylock)
144 int (lutex unsigned-long))
146 (define-alien-routine ("lutex_unlock" %lutex-unlock)
147 int (lutex unsigned-long))
149 (define-alien-routine ("lutex_destroy" %lutex-destroy)
150 int (lutex unsigned-long))
152 ;; FIXME: Defining a whole bunch of alien-type machinery just for
153 ;; passing primitive lutex objects directly to foreign functions
154 ;; doesn't seem like fun right now. So instead we just manually
155 ;; pin the lutex, get its address, and let the callee untag it.
156 (defmacro with-lutex-address ((name lutex) &body body)
157 `(let ((,name ,lutex))
158 (with-pinned-objects (,name)
159 (let ((,name (get-lisp-obj-address ,name)))
163 (/show0 "Entering MAKE-LUTEX")
164 ;; Suppress GC until the lutex has been properly registered with
167 (let ((lutex (sb!vm::%make-lutex)))
170 (with-lutex-address (lutex lutex)
176 (declaim (inline futex-wait %futex-wait futex-wake))
178 (define-alien-routine ("futex_wait" %futex-wait)
179 int (word unsigned-long) (old-value unsigned-long)
180 (to-sec long) (to-usec unsigned-long))
182 (defun futex-wait (word old to-sec to-usec)
184 (%futex-wait word old to-sec to-usec)))
186 (define-alien-routine "futex_wake"
187 int (word unsigned-long) (n unsigned-long))))
189 ;;; used by debug-int.lisp to access interrupt contexts
190 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
192 (defun sb!vm::current-thread-offset-sap (n)
193 (declare (type (unsigned-byte 27) n))
194 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
195 (* n sb!vm:n-word-bytes)))
198 (defun sb!vm::current-thread-offset-sap (n)
199 (declare (type (unsigned-byte 27) n))
200 (sb!vm::current-thread-offset-sap n))
205 (declaim (inline get-spinlock release-spinlock))
207 ;;; Should always be called with interrupts disabled.
208 (defun get-spinlock (spinlock)
209 (declare (optimize (speed 3) (safety 0)))
210 (let* ((new *current-thread*)
211 (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
214 (error "Recursive lock attempt on ~S." spinlock))
217 (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
219 (return-from get-spinlock t))))
220 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
221 ;; If interrupts are disabled, but we are allowed to
222 ;; enabled them, check for pending interrupts every once
223 ;; in a while. %CHECK-INTERRUPTS is taking shortcuts, make
224 ;; sure that deferrables are unblocked by doing an empty
225 ;; WITH-INTERRUPTS once.
229 (loop repeat 128 do (cas)) ; 128 is arbitrary here
230 (sb!unix::%check-interrupts)))
234 (defun release-spinlock (spinlock)
235 (declare (optimize (speed 3) (safety 0)))
236 ;; On x86 and x86-64 we can get away with no memory barriers, (see
237 ;; Linux kernel mailing list "spin_unlock optimization(i386)"
238 ;; thread, summary at
239 ;; http://kt.iserv.nl/kernel-traffic/kt19991220_47.html#1.
241 ;; If the compiler may reorder this with other instructions, insert
242 ;; compiler barrier here.
244 ;; FIXME: this does not work on SMP Pentium Pro and OOSTORE systems,
245 ;; neither on most non-x86 architectures (but we don't have threads
247 (setf (spinlock-value spinlock) nil))
253 (setf (fdocumentation 'make-mutex 'function)
255 (fdocumentation 'mutex-name 'function)
256 "The name of the mutex. Setfable.")
258 #!+(and sb-thread (not sb-lutex))
260 (define-structure-slot-addressor mutex-state-address
263 ;; Important: current code assumes these are fixnums or other
264 ;; lisp objects that don't need pinning.
265 (defconstant +lock-free+ 0)
266 (defconstant +lock-taken+ 1)
267 (defconstant +lock-contested+ 2))
269 (defun mutex-owner (mutex)
270 "Current owner of the mutex, NIL if the mutex is free. Naturally,
271 this is racy by design (another thread may acquire the mutex after
272 this function returns), it is intended for informative purposes. For
273 testing whether the current thread is holding a mutex see
275 ;; Make sure to get the current value.
276 (sb!ext:compare-and-swap (mutex-%owner mutex) nil nil))
278 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
280 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
281 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
282 non-NIL and the mutex is in use, sleep until it is available.
284 Note: using GET-MUTEX to assign a MUTEX to another thread then the
285 current one is not recommended, and liable to be deprecated.
287 GET-MUTEX is not interrupt safe. The correct way to call it is:
291 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
294 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
295 call while the mutex is in an inconsistent state while
296 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
298 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
300 (declare (type mutex mutex) (optimize (speed 3))
301 #!-sb-thread (ignore waitp))
303 (setq new-owner *current-thread*))
304 (let ((old (mutex-%owner mutex)))
305 (when (eq new-owner old)
306 (error "Recursive lock attempt ~S." mutex))
309 (error "Strange deadlock on ~S in an unithreaded build?" mutex)))
311 (setf (mutex-%owner mutex) new-owner)
314 ;; FIXME: Lutexes do not currently support deadlines, as at least
315 ;; on Darwin pthread_foo_timedbar functions are not supported:
316 ;; this means that we probably need to use the Carbon multiprocessing
317 ;; functions on Darwin.
319 ;; FIXME: This is definitely not interrupt safe: what happens if
320 ;; we get hit (1) during the lutex calls (ok, they may be safe,
321 ;; but has that been checked?) (2) after the lutex call, but
322 ;; before setting the mutex owner.
324 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
326 (with-interrupts (%lutex-lock lutex))
327 (%lutex-trylock lutex))))
328 (setf (mutex-%owner mutex) new-owner)
331 ;; This is a direct translation of the Mutex 2 algorithm from
332 ;; "Futexes are Tricky" by Ulrich Drepper.
333 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
336 (unless (or (eql +lock-free+ old) (not waitp))
339 (when (or (eql +lock-contested+ old)
340 (not (eql +lock-free+
341 (sb!ext:compare-and-swap (mutex-state mutex)
344 ;; Wait on the contested lock.
346 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
347 (case (with-pinned-objects (mutex)
348 (futex-wait (mutex-state-address mutex)
349 (get-lisp-obj-address +lock-contested+)
352 ((1) (signal-deadline))
354 (otherwise (return))))))
355 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
359 (unless (eql +lock-free+ old)
361 (cond ((eql +lock-free+ old)
362 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
365 (bug "Old owner in free mutex: ~S" prev))
368 (bug "Failed to acquire lock with WAITP."))))))
370 (defun release-mutex (mutex &key (if-not-owner :punt))
372 "Release MUTEX by setting it to NIL. Wake up threads waiting for
375 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
378 If the current thread is not the owner of the mutex then it silently
379 returns without doing anything (if IF-NOT-OWNER is :PUNT), signals a
380 WARNING (if IF-NOT-OWNER is :WARN), or releases the mutex anyway (if
381 IF-NOT-OWNER is :FORCE)."
382 (declare (type mutex mutex))
383 ;; Order matters: set owner to NIL before releasing state.
384 (let* ((self *current-thread*)
385 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
386 (unless (eql self old-owner)
388 ((:punt) (return-from release-mutex nil))
390 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner))
394 (setf (mutex-%owner mutex) nil)
396 (with-lutex-address (lutex (mutex-lutex mutex))
397 (%lutex-unlock lutex))
399 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
400 ;; unsigned-byte type this can be used:
402 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
403 ;; (unless (eql old +lock-free+)
404 ;; (setf (mutex-state mutex) +lock-free+)
405 ;; (with-pinned-objects (mutex)
406 ;; (futex-wake (mutex-state-address mutex) 1))))
407 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
408 +lock-taken+ +lock-free+)))
409 (when (eql old +lock-contested+)
410 (sb!ext:compare-and-swap (mutex-state mutex)
411 +lock-contested+ +lock-free+)
412 (with-pinned-objects (mutex)
413 (futex-wake (mutex-state-address mutex) 1))))
417 ;;;; Waitqueues/condition variables
419 (defstruct (waitqueue (:constructor %make-waitqueue))
422 (name nil :type (or null simple-string))
423 #!+(and sb-lutex sb-thread)
428 (defun make-waitqueue (&key name)
430 "Create a waitqueue."
431 (%make-waitqueue :name name))
434 (setf (fdocumentation 'waitqueue-name 'function)
435 "The name of the waitqueue. Setfable.")
437 #!+(and sb-thread (not sb-lutex))
438 (define-structure-slot-addressor waitqueue-data-address
442 (defun condition-wait (queue mutex)
444 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
445 thread may subsequently notify us using CONDITION-NOTIFY, at which
446 time we reacquire MUTEX and return to the caller."
447 #!-sb-thread (declare (ignore queue))
449 #!-sb-thread (error "Not supported in unithread builds.")
451 (let ((me *current-thread*))
452 (assert (eq me (mutex-%owner mutex)))
453 (/show0 "CONDITION-WAITing")
455 ;; Need to disable interrupts so that we don't miss setting the
456 ;; owner on our way out. (pthread_cond_wait handles the actual
461 (setf (mutex-%owner mutex) nil)
462 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
463 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
464 (with-local-interrupts
465 (%lutex-wait queue-lutex-address mutex-lutex-address)))))
466 (setf (mutex-%owner mutex) me)))
468 ;; Need to disable interrupts so that we don't miss grabbing the
469 ;; mutex on our way out.
472 ;; This setf becomes visible to other CPUS due to the usual
473 ;; memory barrier semantics of lock acquire/release. This must
474 ;; not be moved into the loop else wakeups may be lost upon
475 ;; continuing after a deadline or EINTR.
476 (setf (waitqueue-data queue) me)
478 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
479 (case (unwind-protect
480 (with-pinned-objects (queue me)
481 ;; RELEASE-MUTEX is purposefully as close to
482 ;; FUTEX-WAIT as possible to reduce the size
483 ;; of the window where WAITQUEUE-DATA may be
484 ;; set by a notifier.
485 (release-mutex mutex)
486 ;; Now we go to sleep using futex-wait. If
487 ;; anyone else manages to grab MUTEX and call
488 ;; CONDITION-NOTIFY during this comment, it
489 ;; will change queue->data, and so futex-wait
490 ;; returns immediately instead of sleeping.
491 ;; Ergo, no lost wakeup. We may get spurious
492 ;; wakeups, but that's ok.
493 (allow-with-interrupts
494 (futex-wait (waitqueue-data-address queue)
495 (get-lisp-obj-address me)
496 ;; our way if saying "no
500 ;; If we are interrupted while waiting, we should
501 ;; do these things before returning. Ideally, in
502 ;; the case of an unhandled signal, we should do
503 ;; them before entering the debugger, but this is
504 ;; better than nothing.
505 (allow-with-interrupts (get-mutex mutex)))
507 ((1) (signal-deadline))
510 ;; EWOULDBLOCK, -1 here, is the possible spurious wakeup
511 ;; case. 0 is the normal wakeup.
512 (otherwise (return)))))))))
514 (defun condition-notify (queue &optional (n 1))
516 "Notify N threads waiting on QUEUE. The same mutex that is used in
517 the corresponding CONDITION-WAIT must be held by this thread during
519 #!-sb-thread (declare (ignore queue n))
520 #!-sb-thread (error "Not supported in unithread builds.")
522 (declare (type (and fixnum (integer 1)) n))
523 (/show0 "Entering CONDITION-NOTIFY")
527 (with-lutex-address (lutex (waitqueue-lutex queue))
528 (%lutex-wake lutex n))
529 ;; no problem if >1 thread notifies during the comment in
530 ;; condition-wait: as long as the value in queue-data isn't the
531 ;; waiting thread's id, it matters not what it is
532 ;; XXX we should do something to ensure that the result of this setf
533 ;; is visible to all CPUs
535 (let ((me *current-thread*))
537 (setf (waitqueue-data queue) me)
538 (with-pinned-objects (queue)
539 (futex-wake (waitqueue-data-address queue) n))))))
541 (defun condition-broadcast (queue)
543 "Notify all threads waiting on QUEUE."
544 (condition-notify queue
545 ;; On a 64-bit platform truncating M-P-F to an int
546 ;; results in -1, which wakes up only one thread.
548 most-positive-fixnum)))
553 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
555 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
556 should be considered an implementation detail, and may change in the
558 (name nil :type (or null simple-string))
559 (%count 0 :type (integer 0))
560 (waitcount 0 :type (integer 0))
562 (queue (make-waitqueue)))
564 (setf (fdocumentation 'semaphore-name 'function)
565 "The name of the semaphore INSTANCE. Setfable.")
567 (declaim (inline semaphore-count))
568 (defun semaphore-count (instance)
569 "Returns the current count of the semaphore INSTANCE."
570 (semaphore-%count instance))
572 (defun make-semaphore (&key name (count 0))
574 "Create a semaphore with the supplied COUNT and NAME."
575 (%make-semaphore name count))
577 (defun wait-on-semaphore (semaphore)
579 "Decrement the count of SEMAPHORE if the count would not be
580 negative. Else blocks until the semaphore can be decremented."
581 ;; A more direct implementation based directly on futexes should be
584 ;; We need to disable interrupts so that we don't forget to
585 ;; decrement the waitcount (which would happen if an asynch
586 ;; interrupt should catch us on our way out from the loop.)
587 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
588 ;; Quick check: is it positive? If not, enter the wait loop.
589 (let ((count (semaphore-%count semaphore)))
591 (setf (semaphore-%count semaphore) (1- count))
594 (incf (semaphore-waitcount semaphore))
595 (loop until (plusp (setf count (semaphore-%count semaphore)))
596 do (condition-wait (semaphore-queue semaphore)
597 (semaphore-mutex semaphore)))
598 (setf (semaphore-%count semaphore) (1- count)))
599 (decf (semaphore-waitcount semaphore)))))))
601 (defun signal-semaphore (semaphore &optional (n 1))
603 "Increment the count of SEMAPHORE by N. If there are threads waiting
604 on this semaphore, then N of them is woken up."
605 (declare (type (integer 1) n))
606 ;; Need to disable interrupts so that we don't lose a wakeup after
607 ;; we have incremented the count.
608 (with-system-mutex ((semaphore-mutex semaphore))
609 (let ((waitcount (semaphore-waitcount semaphore))
610 (count (incf (semaphore-%count semaphore) n)))
611 (when (plusp waitcount)
612 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
615 ;;;; Job control, independent listeners
618 (lock (make-mutex :name "session lock"))
620 (interactive-threads nil)
621 (interactive-threads-queue (make-waitqueue)))
623 (defvar *session* nil)
625 ;;; The debugger itself tries to acquire the session lock, don't let
626 ;;; funny situations (like getting a sigint while holding the session
627 ;;; lock) occur. At the same time we need to allow interrupts while
628 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
629 ;;; be interruptible.
631 ;;; Take care: we sometimes need to obtain the session lock while
632 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
633 ;;; _after_ getting a session lock! (Deadlock risk.)
635 ;;; FIXME: It would be good to have ordered locks to ensure invariants
637 (defmacro with-session-lock ((session) &body body)
638 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
641 (defun new-session ()
642 (make-session :threads (list *current-thread*)
643 :interactive-threads (list *current-thread*)))
645 (defun init-job-control ()
646 (/show0 "Entering INIT-JOB-CONTROL")
647 (setf *session* (new-session))
648 (/show0 "Exiting INIT-JOB-CONTROL"))
650 (defun %delete-thread-from-session (thread session)
651 (with-session-lock (session)
652 (setf (session-threads session)
653 (delete thread (session-threads session))
654 (session-interactive-threads session)
655 (delete thread (session-interactive-threads session)))))
657 (defun call-with-new-session (fn)
658 (%delete-thread-from-session *current-thread* *session*)
659 (let ((*session* (new-session)))
662 (defmacro with-new-session (args &body forms)
663 (declare (ignore args)) ;for extensibility
664 (sb!int:with-unique-names (fb-name)
665 `(labels ((,fb-name () ,@forms))
666 (call-with-new-session (function ,fb-name)))))
668 ;;; Remove thread from its session, if it has one.
670 (defun handle-thread-exit (thread)
671 (/show0 "HANDLING THREAD EXIT")
673 (with-all-threads-lock
674 (setf (thread-%alive-p thread) nil)
675 (setf (thread-os-thread thread) nil)
676 (setq *all-threads* (delete thread *all-threads*))
678 (%delete-thread-from-session thread *session*)))
681 (/show0 "FREEING MUTEX LUTEX")
682 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
683 (%lutex-destroy lutex))))
685 (defun terminate-session ()
687 "Kill all threads in session except for this one. Does nothing if current
688 thread is not the foreground thread."
689 ;; FIXME: threads created in other threads may escape termination
691 (with-session-lock (*session*)
692 (and (eq *current-thread*
693 (car (session-interactive-threads *session*)))
694 (session-threads *session*)))))
695 ;; do the kill after dropping the mutex; unwind forms in dying
696 ;; threads may want to do session things
697 (dolist (thread to-kill)
698 (unless (eq thread *current-thread*)
699 ;; terminate the thread but don't be surprised if it has
700 ;; exited in the meantime
701 (handler-case (terminate-thread thread)
702 (interrupt-thread-error ()))))))
704 ;;; called from top of invoke-debugger
705 (defun debugger-wait-until-foreground-thread (stream)
706 "Returns T if thread had been running in background, NIL if it was
708 (declare (ignore stream))
712 (with-session-lock (*session*)
713 (not (member *current-thread*
714 (session-interactive-threads *session*))))
717 (defun get-foreground ()
720 (let ((was-foreground t))
722 (/show0 "Looping in GET-FOREGROUND")
723 (with-session-lock (*session*)
724 (let ((int-t (session-interactive-threads *session*)))
725 (when (eq (car int-t) *current-thread*)
726 (unless was-foreground
727 (format *query-io* "Resuming thread ~A~%" *current-thread*))
728 (return-from get-foreground t))
729 (setf was-foreground nil)
730 (unless (member *current-thread* int-t)
731 (setf (cdr (last int-t))
732 (list *current-thread*)))
734 (session-interactive-threads-queue *session*)
735 (session-lock *session*)))))))
737 (defun release-foreground (&optional next)
739 "Background this thread. If NEXT is supplied, arrange for it to
740 have the foreground next."
741 #!-sb-thread (declare (ignore next))
744 (with-session-lock (*session*)
745 (when (rest (session-interactive-threads *session*))
746 (setf (session-interactive-threads *session*)
747 (delete *current-thread* (session-interactive-threads *session*))))
749 (setf (session-interactive-threads *session*)
751 (delete next (session-interactive-threads *session*)))))
752 (condition-broadcast (session-interactive-threads-queue *session*))))
754 (defun foreground-thread ()
755 (car (session-interactive-threads *session*)))
757 (defun make-listener-thread (tty-name)
758 (assert (probe-file tty-name))
759 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
760 (out (sb!unix:unix-dup in))
761 (err (sb!unix:unix-dup in)))
762 (labels ((thread-repl ()
763 (sb!unix::unix-setsid)
764 (let* ((sb!impl::*stdin*
765 (make-fd-stream in :input t :buffering :line
768 (make-fd-stream out :output t :buffering :line
771 (make-fd-stream err :output t :buffering :line
774 (make-fd-stream err :input t :output t
777 (sb!impl::*descriptor-handlers* nil))
780 (sb!impl::toplevel-repl nil)
781 (sb!int:flush-standard-output-streams))))))
782 (make-thread #'thread-repl))))
787 (defun make-thread (function &key name)
789 "Create a new thread of NAME that runs FUNCTION. When the function
790 returns the thread exits. The return values of FUNCTION are kept
791 around and can be retrieved by JOIN-THREAD."
792 #!-sb-thread (declare (ignore function name))
793 #!-sb-thread (error "Not supported in unithread builds.")
795 (let* ((thread (%make-thread :name name))
796 (setup-sem (make-semaphore :name "Thread setup semaphore"))
797 (real-function (coerce function 'function))
800 ;; In time we'll move some of the binding presently done in C
803 ;; KLUDGE: Here we have a magic list of variables that are
804 ;; not thread-safe for one reason or another. As people
805 ;; report problems with the thread safety of certain
806 ;; variables, (e.g. "*print-case* in multiple threads
807 ;; broken", sbcl-devel 2006-07-14), we add a few more
808 ;; bindings here. The Right Thing is probably some variant
809 ;; of Allegro's *cl-default-special-bindings*, as that is at
810 ;; least accessible to users to secure their own libraries.
813 ;; As it is, this lambda must not cons until we are ready
814 ;; to run GC. Be very careful.
815 (let* ((*current-thread* thread)
816 (*restart-clusters* nil)
817 (*handler-clusters* (sb!kernel::initial-handler-clusters))
818 (*condition-restarts* nil)
819 (sb!impl::*deadline* nil)
820 (sb!impl::*step-out* nil)
821 ;; internal printer variables
822 (sb!impl::*previous-case* nil)
823 (sb!impl::*previous-readtable-case* nil)
825 (sb!impl::*merge-sort-temp-vector* empty)
826 (sb!impl::*zap-array-data-temp* empty)
827 (sb!impl::*internal-symbol-output-fun* nil)
828 (sb!impl::*descriptor-handlers* nil)) ; serve-event
830 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
831 (setf (thread-os-thread thread) (current-thread-os-thread))
832 (with-mutex ((thread-result-lock thread))
833 (with-all-threads-lock
834 (push thread *all-threads*))
835 (with-session-lock (*session*)
836 (push thread (session-threads *session*)))
837 (setf (thread-%alive-p thread) t)
838 (signal-semaphore setup-sem)
839 ;; can't use handling-end-of-the-world, because that flushes
840 ;; output streams, and we don't necessarily have any (or we
841 ;; could be sharing them)
842 (catch 'sb!impl::toplevel-catcher
843 (catch 'sb!impl::%end-of-the-world
847 "~~@<Terminate this thread (~A)~~@:>"
851 (with-local-interrupts
852 ;; Now that most things have a chance
853 ;; to work properly without messing up
854 ;; other threads, it's time to enable
856 (sb!unix::unblock-deferrable-signals)
857 (setf (thread-result thread)
860 (funcall real-function))))
861 ;; Try to block deferrables. An
862 ;; interrupt may unwind it, but for a
863 ;; normal exit it prevents interrupt
865 (block-deferrable-signals))
866 ;; We're going down, can't handle interrupts
867 ;; sanely anymore. GC remains enabled.
868 (block-deferrable-signals)
869 ;; We don't want to run interrupts in a dead
870 ;; thread when we leave WITHOUT-INTERRUPTS.
871 ;; This potentially causes important
872 ;; interupts to be lost: SIGINT comes to
874 (setq *interrupt-pending* nil)
875 (handle-thread-exit thread))))))))
877 ;; If the starting thread is stopped for gc before it signals the
878 ;; semaphore then we'd be stuck.
879 (assert (not *gc-inhibit*))
880 ;; Keep INITIAL-FUNCTION pinned until the child thread is
881 ;; initialized properly. Wrap the whole thing in
882 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
885 (with-pinned-objects (initial-function)
888 (get-lisp-obj-address initial-function))))
889 (when (zerop os-thread)
890 (error "Can't create a new thread"))
891 (wait-on-semaphore setup-sem)
894 (define-condition join-thread-error (error)
895 ((thread :reader join-thread-error-thread :initarg :thread))
897 (:documentation "Joining thread failed.")
898 (:report (lambda (c s)
899 (format s "Joining thread failed: thread ~A ~
900 has not returned normally."
901 (join-thread-error-thread c)))))
904 (setf (fdocumentation 'join-thread-error-thread 'function)
905 "The thread that we failed to join.")
907 (defun join-thread (thread &key (default nil defaultp))
909 "Suspend current thread until THREAD exits. Returns the result
910 values of the thread function. If the thread does not exit normally,
911 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
912 (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
913 (cond ((car (thread-result thread))
914 (return-from join-thread
915 (values-list (cdr (thread-result thread)))))
917 (return-from join-thread default))))
918 (error 'join-thread-error :thread thread))
920 (defun destroy-thread (thread)
922 "Deprecated. Same as TERMINATE-THREAD."
923 (terminate-thread thread))
925 (define-condition interrupt-thread-error (error)
926 ((thread :reader interrupt-thread-error-thread :initarg :thread))
928 (:documentation "Interrupting thread failed.")
929 (:report (lambda (c s)
930 (format s "Interrupt thread failed: thread ~A has exited."
931 (interrupt-thread-error-thread c)))))
934 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
935 "The thread that was not interrupted.")
937 (defmacro with-interruptions-lock ((thread) &body body)
938 `(with-system-mutex ((thread-interruptions-lock ,thread))
941 ;;; Called from the signal handler.
943 (defun run-interruption ()
944 (let ((interruption (with-interruptions-lock (*current-thread*)
945 (pop (thread-interruptions *current-thread*)))))
946 ;; If there is more to do, then resignal and let the normal
947 ;; interrupt deferral mechanism take care of the rest. From the
948 ;; OS's point of view the signal we are in the handler for is no
949 ;; longer pending, so the signal will not be lost.
950 (when (thread-interruptions *current-thread*)
951 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
953 (funcall interruption))))
955 (defun interrupt-thread (thread function)
957 "Interrupt the live THREAD and make it run FUNCTION. A moderate
958 degree of care is expected for use of INTERRUPT-THREAD, due to its
959 nature: if you interrupt a thread that was holding important locks
960 then do something that turns out to need those locks, you probably
961 won't like the effect. FUNCTION runs with interrupts disabled, but
962 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
963 enable interrupts (GET-MUTEX when contended, for instance) so the
964 first thing to do is usually a WITH-INTERRUPTS or a
965 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
966 run in same the order they were sent."
968 (declare (ignore thread))
970 (with-interrupt-bindings
971 (with-interrupts (funcall function)))
973 (let ((os-thread (thread-os-thread thread)))
974 (cond ((not os-thread)
975 (error 'interrupt-thread-error :thread thread))
977 (with-interruptions-lock (thread)
978 ;; Append to the end of the interruptions queue. It's
979 ;; O(N), but it does not hurt to slow interruptors down a
980 ;; bit when the queue gets long.
981 (setf (thread-interruptions thread)
982 (append (thread-interruptions thread)
985 (allow-with-interrupts
986 (funcall function))))))))
987 (when (minusp (kill-safely os-thread sb!unix:sigpipe))
988 (error 'interrupt-thread-error :thread thread))))))
990 (defun terminate-thread (thread)
992 "Terminate the thread identified by THREAD, by causing it to run
993 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
994 (interrupt-thread thread 'sb!ext:quit))
996 (define-alien-routine "thread_yield" int)
999 (setf (fdocumentation 'thread-yield 'function)
1000 "Yield the processor to other threads.")
1002 ;;; internal use only. If you think you need to use these, either you
1003 ;;; are an SBCL developer, are doing something that you should discuss
1004 ;;; with an SBCL developer first, or are doing something that you
1005 ;;; should probably discuss with a professional psychiatrist first
1008 (defun %thread-sap (thread)
1009 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
1010 (target (thread-os-thread thread)))
1012 (when (sap= thread-sap (int-sap 0)) (return nil))
1013 (let ((os-thread (sap-ref-word thread-sap
1014 (* sb!vm:n-word-bytes
1015 sb!vm::thread-os-thread-slot))))
1016 (when (= os-thread target) (return thread-sap))
1018 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
1019 sb!vm::thread-next-slot)))))))
1021 (defun %symbol-value-in-thread (symbol thread)
1023 ;; Prevent the dead from dying completely while we look for the
1025 (with-all-threads-lock
1026 (if (thread-alive-p thread)
1027 (let* ((offset (* sb!vm:n-word-bytes
1028 (sb!vm::symbol-tls-index symbol)))
1029 (tl-val (sap-ref-word (%thread-sap thread) offset)))
1030 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
1032 (return-from %symbol-value-in-thread
1033 (values (make-lisp-obj tl-val) t))))
1034 (return-from %symbol-value-in-thread (values nil nil))))
1036 (error "Cannot read thread-local symbol value: ~S unbound in ~S"
1039 (defun %set-symbol-value-in-thread (symbol thread value)
1041 (with-pinned-objects (value)
1042 ;; Prevent the dead from dying completely while we look for
1044 (with-all-threads-lock
1045 (if (thread-alive-p thread)
1046 (let* ((offset (* sb!vm:n-word-bytes
1047 (sb!vm::symbol-tls-index symbol)))
1048 (sap (%thread-sap thread))
1049 (tl-val (sap-ref-word sap offset)))
1050 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
1052 (setf (sap-ref-word sap offset)
1053 (get-lisp-obj-address value)))
1054 (return-from %set-symbol-value-in-thread (values value t)))
1055 (return-from %set-symbol-value-in-thread (values nil nil)))))
1057 (error "Cannot set thread-local symbol value: ~S unbound in ~S"
1060 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1061 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1066 (defun thread-stepping ()
1068 (sap-ref-word (current-thread-sap)
1069 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1071 (defun (setf thread-stepping) (value)
1072 (setf (sap-ref-word (current-thread-sap)
1073 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1074 (get-lisp-obj-address value)))