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 tranlation 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)
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 Signals a WARNING if current thread is not the current owner of the
380 (declare (type mutex mutex))
381 ;; Order matters: set owner to NIL before releasing state.
382 (let* ((self *current-thread*)
383 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
384 (unless (eql self old-owner)
385 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
386 (setf (mutex-%owner mutex) nil)))
390 (with-lutex-address (lutex (mutex-lutex mutex))
391 (%lutex-unlock lutex))
393 ;; FIXME: once ATOMIC-INCF supports struct slots with word sized
394 ;; unsigned-byte type this can be used:
396 ;; (let ((old (sb!ext:atomic-incf (mutex-state mutex) -1)))
397 ;; (unless (eql old +lock-free+)
398 ;; (setf (mutex-state mutex) +lock-free+)
399 ;; (with-pinned-objects (mutex)
400 ;; (futex-wake (mutex-state-address mutex) 1))))
401 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
402 +lock-taken+ +lock-free+)))
403 (when (eql old +lock-contested+)
404 (sb!ext:compare-and-swap (mutex-state mutex)
405 +lock-contested+ +lock-free+)
406 (with-pinned-objects (mutex)
407 (futex-wake (mutex-state-address mutex) 1))))
411 ;;;; Waitqueues/condition variables
413 (defstruct (waitqueue (:constructor %make-waitqueue))
416 (name nil :type (or null simple-string))
417 #!+(and sb-lutex sb-thread)
422 (defun make-waitqueue (&key name)
424 "Create a waitqueue."
425 (%make-waitqueue :name name))
428 (setf (fdocumentation 'waitqueue-name 'function)
429 "The name of the waitqueue. Setfable.")
431 #!+(and sb-thread (not sb-lutex))
432 (define-structure-slot-addressor waitqueue-data-address
436 (defun condition-wait (queue mutex)
438 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
439 thread may subsequently notify us using CONDITION-NOTIFY, at which
440 time we reacquire MUTEX and return to the caller."
441 #!-sb-thread (declare (ignore queue))
443 #!-sb-thread (error "Not supported in unithread builds.")
445 (let ((me *current-thread*))
446 (assert (eq me (mutex-%owner mutex)))
447 (/show0 "CONDITION-WAITing")
449 ;; Need to disable interrupts so that we don't miss setting the
450 ;; owner on our way out. (pthread_cond_wait handles the actual
455 (setf (mutex-%owner mutex) nil)
456 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
457 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
458 (with-local-interrupts
459 (%lutex-wait queue-lutex-address mutex-lutex-address)))))
460 (setf (mutex-%owner mutex) me)))
462 ;; Need to disable interrupts so that we don't miss grabbing the
463 ;; mutex on our way out.
466 (let ((me *current-thread*))
467 ;; This setf becomes visible to other CPUS due to the
468 ;; usual memory barrier semantics of lock
470 (setf (waitqueue-data queue) me)
471 (release-mutex mutex)
472 ;; Now we go to sleep using futex-wait. If anyone else
473 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
474 ;; this comment, it will change queue->data, and so
475 ;; futex-wait returns immediately instead of sleeping.
476 ;; Ergo, no lost wakeup. We may get spurious wakeups, but
479 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
480 (case (with-pinned-objects (queue me)
481 (allow-with-interrupts
482 (futex-wait (waitqueue-data-address queue)
483 (get-lisp-obj-address me)
484 ;; our way if saying "no
488 ((1) (signal-deadline))
490 (otherwise (return))))))
491 ;; If we are interrupted while waiting, we should do these
492 ;; things before returning. Ideally, in the case of an
493 ;; unhandled signal, we should do them before entering the
494 ;; debugger, but this is better than nothing.
495 (get-mutex mutex)))))
497 (defun condition-notify (queue &optional (n 1))
499 "Notify N threads waiting on QUEUE. The same mutex that is used in
500 the correspoinding condition-wait must be held by this thread during
502 #!-sb-thread (declare (ignore queue n))
503 #!-sb-thread (error "Not supported in unithread builds.")
505 (declare (type (and fixnum (integer 1)) n))
506 (/show0 "Entering CONDITION-NOTIFY")
510 (with-lutex-address (lutex (waitqueue-lutex queue))
511 (%lutex-wake lutex n))
512 ;; no problem if >1 thread notifies during the comment in
513 ;; condition-wait: as long as the value in queue-data isn't the
514 ;; waiting thread's id, it matters not what it is
515 ;; XXX we should do something to ensure that the result of this setf
516 ;; is visible to all CPUs
518 (let ((me *current-thread*))
520 (setf (waitqueue-data queue) me)
521 (with-pinned-objects (queue)
522 (futex-wake (waitqueue-data-address queue) n))))))
524 (defun condition-broadcast (queue)
526 "Notify all threads waiting on QUEUE."
527 (condition-notify queue
528 ;; On a 64-bit platform truncating M-P-F to an int
529 ;; results in -1, which wakes up only one thread.
531 most-positive-fixnum)))
536 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
538 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
539 should be considered an implementation detail, and may change in the
541 (name nil :type (or null simple-string))
542 (%count 0 :type (integer 0))
543 (waitcount 0 :type (integer 0))
545 (queue (make-waitqueue)))
547 (setf (fdocumentation 'semaphore-name 'function)
548 "The name of the semaphore INSTANCE. Setfable.")
550 (declaim (inline semaphore-count))
551 (defun semaphore-count (instance)
552 "Returns the current count of the semaphore INSTANCE."
553 (semaphore-%count instance))
555 (defun make-semaphore (&key name (count 0))
557 "Create a semaphore with the supplied COUNT and NAME."
558 (%make-semaphore name count))
560 (defun wait-on-semaphore (semaphore)
562 "Decrement the count of SEMAPHORE if the count would not be
563 negative. Else blocks until the semaphore can be decremented."
564 ;; A more direct implementation based directly on futexes should be
567 ;; We need to disable interrupts so that we don't forget to
568 ;; decrement the waitcount (which would happen if an asynch
569 ;; interrupt should catch us on our way out from the loop.)
570 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
571 ;; Quick check: is it positive? If not, enter the wait loop.
572 (let ((count (semaphore-%count semaphore)))
574 (setf (semaphore-%count semaphore) (1- count))
577 (incf (semaphore-waitcount semaphore))
578 (loop until (plusp (setf count (semaphore-%count semaphore)))
579 do (condition-wait (semaphore-queue semaphore)
580 (semaphore-mutex semaphore)))
581 (setf (semaphore-%count semaphore) (1- count)))
582 (decf (semaphore-waitcount semaphore)))))))
584 (defun signal-semaphore (semaphore &optional (n 1))
586 "Increment the count of SEMAPHORE by N. If there are threads waiting
587 on this semaphore, then N of them is woken up."
588 (declare (type (integer 1) n))
589 ;; Need to disable interrupts so that we don't lose a wakeup after
590 ;; we have incremented the count.
591 (with-system-mutex ((semaphore-mutex semaphore))
592 (let ((waitcount (semaphore-waitcount semaphore))
593 (count (incf (semaphore-%count semaphore) n)))
594 (when (plusp waitcount)
595 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
598 ;;;; Job control, independent listeners
601 (lock (make-mutex :name "session lock"))
603 (interactive-threads nil)
604 (interactive-threads-queue (make-waitqueue)))
606 (defvar *session* nil)
608 ;;; The debugger itself tries to acquire the session lock, don't let
609 ;;; funny situations (like getting a sigint while holding the session
610 ;;; lock) occur. At the same time we need to allow interrupts while
611 ;;; *waiting* for the session lock for things like GET-FOREGROUND to
612 ;;; be interruptible.
614 ;;; Take care: we sometimes need to obtain the session lock while
615 ;;; holding on to *ALL-THREADS-LOCK*, so we must _never_ obtain it
616 ;;; _after_ getting a session lock! (Deadlock risk.)
618 ;;; FIXME: It would be good to have ordered locks to ensure invariants
620 (defmacro with-session-lock ((session) &body body)
621 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
624 (defun new-session ()
625 (make-session :threads (list *current-thread*)
626 :interactive-threads (list *current-thread*)))
628 (defun init-job-control ()
629 (/show0 "Entering INIT-JOB-CONTROL")
630 (setf *session* (new-session))
631 (/show0 "Exiting INIT-JOB-CONTROL"))
633 (defun %delete-thread-from-session (thread session)
634 (with-session-lock (session)
635 (setf (session-threads session)
636 (delete thread (session-threads session))
637 (session-interactive-threads session)
638 (delete thread (session-interactive-threads session)))))
640 (defun call-with-new-session (fn)
641 (%delete-thread-from-session *current-thread* *session*)
642 (let ((*session* (new-session)))
645 (defmacro with-new-session (args &body forms)
646 (declare (ignore args)) ;for extensibility
647 (sb!int:with-unique-names (fb-name)
648 `(labels ((,fb-name () ,@forms))
649 (call-with-new-session (function ,fb-name)))))
651 ;;; Remove thread from its session, if it has one.
653 (defun handle-thread-exit (thread)
654 (/show0 "HANDLING THREAD EXIT")
656 (with-all-threads-lock
657 (setf (thread-%alive-p thread) nil)
658 (setf (thread-os-thread thread) nil)
659 (setq *all-threads* (delete thread *all-threads*))
661 (%delete-thread-from-session thread *session*)))
664 (/show0 "FREEING MUTEX LUTEX")
665 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
666 (%lutex-destroy lutex))))
668 (defun terminate-session ()
670 "Kill all threads in session except for this one. Does nothing if current
671 thread is not the foreground thread."
672 ;; FIXME: threads created in other threads may escape termination
674 (with-session-lock (*session*)
675 (and (eq *current-thread*
676 (car (session-interactive-threads *session*)))
677 (session-threads *session*)))))
678 ;; do the kill after dropping the mutex; unwind forms in dying
679 ;; threads may want to do session things
680 (dolist (thread to-kill)
681 (unless (eq thread *current-thread*)
682 ;; terminate the thread but don't be surprised if it has
683 ;; exited in the meantime
684 (handler-case (terminate-thread thread)
685 (interrupt-thread-error ()))))))
687 ;;; called from top of invoke-debugger
688 (defun debugger-wait-until-foreground-thread (stream)
689 "Returns T if thread had been running in background, NIL if it was
691 (declare (ignore stream))
695 (with-session-lock (*session*)
696 (not (member *current-thread*
697 (session-interactive-threads *session*))))
700 (defun get-foreground ()
703 (let ((was-foreground t))
705 (/show0 "Looping in GET-FOREGROUND")
706 (with-session-lock (*session*)
707 (let ((int-t (session-interactive-threads *session*)))
708 (when (eq (car int-t) *current-thread*)
709 (unless was-foreground
710 (format *query-io* "Resuming thread ~A~%" *current-thread*))
711 (return-from get-foreground t))
712 (setf was-foreground nil)
713 (unless (member *current-thread* int-t)
714 (setf (cdr (last int-t))
715 (list *current-thread*)))
717 (session-interactive-threads-queue *session*)
718 (session-lock *session*)))))))
720 (defun release-foreground (&optional next)
722 "Background this thread. If NEXT is supplied, arrange for it to
723 have the foreground next."
724 #!-sb-thread (declare (ignore next))
727 (with-session-lock (*session*)
728 (when (rest (session-interactive-threads *session*))
729 (setf (session-interactive-threads *session*)
730 (delete *current-thread* (session-interactive-threads *session*))))
732 (setf (session-interactive-threads *session*)
734 (delete next (session-interactive-threads *session*)))))
735 (condition-broadcast (session-interactive-threads-queue *session*))))
737 (defun foreground-thread ()
738 (car (session-interactive-threads *session*)))
740 (defun make-listener-thread (tty-name)
741 (assert (probe-file tty-name))
742 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
743 (out (sb!unix:unix-dup in))
744 (err (sb!unix:unix-dup in)))
745 (labels ((thread-repl ()
746 (sb!unix::unix-setsid)
747 (let* ((sb!impl::*stdin*
748 (make-fd-stream in :input t :buffering :line
751 (make-fd-stream out :output t :buffering :line
754 (make-fd-stream err :output t :buffering :line
757 (make-fd-stream err :input t :output t
760 (sb!impl::*descriptor-handlers* nil))
763 (sb!impl::toplevel-repl nil)
764 (sb!int:flush-standard-output-streams))))))
765 (make-thread #'thread-repl))))
770 (defun make-thread (function &key name)
772 "Create a new thread of NAME that runs FUNCTION. When the function
773 returns the thread exits. The return values of FUNCTION are kept
774 around and can be retrieved by JOIN-THREAD."
775 #!-sb-thread (declare (ignore function name))
776 #!-sb-thread (error "Not supported in unithread builds.")
778 (let* ((thread (%make-thread :name name))
779 (setup-sem (make-semaphore :name "Thread setup semaphore"))
780 (real-function (coerce function 'function))
783 ;; In time we'll move some of the binding presently done in C
786 ;; KLUDGE: Here we have a magic list of variables that are
787 ;; not thread-safe for one reason or another. As people
788 ;; report problems with the thread safety of certain
789 ;; variables, (e.g. "*print-case* in multiple threads
790 ;; broken", sbcl-devel 2006-07-14), we add a few more
791 ;; bindings here. The Right Thing is probably some variant
792 ;; of Allegro's *cl-default-special-bindings*, as that is at
793 ;; least accessible to users to secure their own libraries.
796 ;; As it is, this lambda must not cons until we are ready
797 ;; to run GC. Be very careful.
798 (let* ((*current-thread* thread)
799 (*restart-clusters* nil)
800 (*handler-clusters* (sb!kernel::initial-handler-clusters))
801 (*condition-restarts* nil)
802 (sb!impl::*deadline* nil)
803 (sb!impl::*step-out* nil)
804 ;; internal printer variables
805 (sb!impl::*previous-case* nil)
806 (sb!impl::*previous-readtable-case* nil)
808 (sb!impl::*merge-sort-temp-vector* empty)
809 (sb!impl::*zap-array-data-temp* empty)
810 (sb!impl::*internal-symbol-output-fun* nil)
811 (sb!impl::*descriptor-handlers* nil)) ; serve-event
813 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
814 (setf (thread-os-thread thread) (current-thread-os-thread))
815 (with-mutex ((thread-result-lock thread))
816 (with-all-threads-lock
817 (push thread *all-threads*))
818 (with-session-lock (*session*)
819 (push thread (session-threads *session*)))
820 (setf (thread-%alive-p thread) t)
821 (signal-semaphore setup-sem)
822 ;; can't use handling-end-of-the-world, because that flushes
823 ;; output streams, and we don't necessarily have any (or we
824 ;; could be sharing them)
825 (catch 'sb!impl::toplevel-catcher
826 (catch 'sb!impl::%end-of-the-world
830 "~~@<Terminate this thread (~A)~~@:>"
834 (with-local-interrupts
835 ;; Now that most things have a chance
836 ;; to work properly without messing up
837 ;; other threads, it's time to enable
839 (sb!unix::unblock-deferrable-signals)
840 (setf (thread-result thread)
843 (funcall real-function))))
844 ;; Try to block deferrables. An
845 ;; interrupt may unwind it, but for a
846 ;; normal exit it prevents interrupt
848 (block-deferrable-signals))
849 ;; We're going down, can't handle interrupts
850 ;; sanely anymore. GC remains enabled.
851 (block-deferrable-signals)
852 ;; We don't want to run interrupts in a dead
853 ;; thread when we leave WITHOUT-INTERRUPTS.
854 ;; This potentially causes important
855 ;; interupts to be lost: SIGINT comes to
857 (setq *interrupt-pending* nil)
858 (handle-thread-exit thread))))))))
860 ;; If the starting thread is stopped for gc before it signals the
861 ;; semaphore then we'd be stuck.
862 (assert (not *gc-inhibit*))
863 ;; Keep INITIAL-FUNCTION pinned until the child thread is
864 ;; initialized properly. Wrap the whole thing in
865 ;; WITHOUT-INTERRUPTS because we pass INITIAL-FUNCTION to another
868 (with-pinned-objects (initial-function)
871 (get-lisp-obj-address initial-function))))
872 (when (zerop os-thread)
873 (error "Can't create a new thread"))
874 (wait-on-semaphore setup-sem)
877 (define-condition join-thread-error (error)
878 ((thread :reader join-thread-error-thread :initarg :thread))
880 (:documentation "Joining thread failed.")
881 (:report (lambda (c s)
882 (format s "Joining thread failed: thread ~A ~
883 has not returned normally."
884 (join-thread-error-thread c)))))
887 (setf (fdocumentation 'join-thread-error-thread 'function)
888 "The thread that we failed to join.")
890 (defun join-thread (thread &key (default nil defaultp))
892 "Suspend current thread until THREAD exits. Returns the result
893 values of the thread function. If the thread does not exit normally,
894 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
895 (with-system-mutex ((thread-result-lock thread) :allow-with-interrupts t)
896 (cond ((car (thread-result thread))
897 (return-from join-thread
898 (values-list (cdr (thread-result thread)))))
900 (return-from join-thread default))))
901 (error 'join-thread-error :thread thread))
903 (defun destroy-thread (thread)
905 "Deprecated. Same as TERMINATE-THREAD."
906 (terminate-thread thread))
908 (define-condition interrupt-thread-error (error)
909 ((thread :reader interrupt-thread-error-thread :initarg :thread))
911 (:documentation "Interrupting thread failed.")
912 (:report (lambda (c s)
913 (format s "Interrupt thread failed: thread ~A has exited."
914 (interrupt-thread-error-thread c)))))
917 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
918 "The thread that was not interrupted.")
920 (defmacro with-interruptions-lock ((thread) &body body)
921 `(with-system-mutex ((thread-interruptions-lock ,thread))
924 ;;; Called from the signal handler.
925 (defun run-interruption ()
926 (let ((interruption (with-interruptions-lock (*current-thread*)
927 (pop (thread-interruptions *current-thread*)))))
928 ;; If there is more to do, then resignal and let the normal
929 ;; interrupt deferral mechanism take care of the rest. From the
930 ;; OS's point of view the signal we are in the handler for is no
931 ;; longer pending, so the signal will not be lost.
932 (when (thread-interruptions *current-thread*)
933 (kill-safely (thread-os-thread *current-thread*) sb!unix:sigpipe))
935 (funcall interruption))))
937 (defun interrupt-thread (thread function)
939 "Interrupt the live THREAD and make it run FUNCTION. A moderate
940 degree of care is expected for use of INTERRUPT-THREAD, due to its
941 nature: if you interrupt a thread that was holding important locks
942 then do something that turns out to need those locks, you probably
943 won't like the effect. FUNCTION runs with interrupts disabled, but
944 WITH-INTERRUPTS is allowed in it. Keep in mind that many things may
945 enable interrupts (GET-MUTEX when contended, for instance) so the
946 first thing to do is usually a WITH-INTERRUPTS or a
947 WITHOUT-INTERRUPTS. Within a thread interrupts are queued, they are
948 run in same the order they were sent."
949 (let ((os-thread (thread-os-thread thread)))
950 (cond ((not os-thread)
951 (error 'interrupt-thread-error :thread thread))
953 (with-interruptions-lock (thread)
954 ;; Append to the end of the interruptions queue. It's
955 ;; O(N), but it does not hurt to slow interruptors down a
956 ;; bit when the queue gets long.
957 (setf (thread-interruptions thread)
958 (append (thread-interruptions thread)
961 (allow-with-interrupts
962 (funcall function))))))))
963 (when (minusp (kill-safely os-thread sb!unix:sigpipe))
964 (error 'interrupt-thread-error :thread thread))))))
966 (defun terminate-thread (thread)
968 "Terminate the thread identified by THREAD, by causing it to run
969 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
970 (interrupt-thread thread 'sb!ext:quit))
972 (define-alien-routine "thread_yield" int)
975 (setf (fdocumentation 'thread-yield 'function)
976 "Yield the processor to other threads.")
978 ;;; internal use only. If you think you need to use these, either you
979 ;;; are an SBCL developer, are doing something that you should discuss
980 ;;; with an SBCL developer first, or are doing something that you
981 ;;; should probably discuss with a professional psychiatrist first
984 (defun %thread-sap (thread)
985 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
986 (target (thread-os-thread thread)))
988 (when (sap= thread-sap (int-sap 0)) (return nil))
989 (let ((os-thread (sap-ref-word thread-sap
990 (* sb!vm:n-word-bytes
991 sb!vm::thread-os-thread-slot))))
992 (when (= os-thread target) (return thread-sap))
994 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
995 sb!vm::thread-next-slot)))))))
997 (defun %symbol-value-in-thread (symbol thread)
999 ;; Prevent the dead from dying completely while we look for the
1001 (with-all-threads-lock
1002 (if (thread-alive-p thread)
1003 (let* ((offset (* sb!vm:n-word-bytes
1004 (sb!vm::symbol-tls-index symbol)))
1005 (tl-val (sap-ref-word (%thread-sap thread) offset)))
1006 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
1008 (return-from %symbol-value-in-thread
1009 (values (make-lisp-obj tl-val) t))))
1010 (return-from %symbol-value-in-thread (values nil nil))))
1012 (error "Cannot read thread-local symbol value: ~S unbound in ~S"
1015 (defun %set-symbol-value-in-thread (symbol thread value)
1017 (with-pinned-objects (value)
1018 ;; Prevent the dead from dying completely while we look for
1020 (with-all-threads-lock
1021 (if (thread-alive-p thread)
1022 (let* ((offset (* sb!vm:n-word-bytes
1023 (sb!vm::symbol-tls-index symbol)))
1024 (sap (%thread-sap thread))
1025 (tl-val (sap-ref-word sap offset)))
1026 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
1028 (setf (sap-ref-word sap offset)
1029 (get-lisp-obj-address value)))
1030 (return-from %set-symbol-value-in-thread (values value t)))
1031 (return-from %set-symbol-value-in-thread (values nil nil)))))
1033 (error "Cannot set thread-local symbol value: ~S unbound in ~S"
1036 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
1037 (sb!vm::locked-symbol-global-value-add symbol-name delta))
1042 (defun thread-stepping ()
1044 (sap-ref-word (current-thread-sap)
1045 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
1047 (defun (setf thread-stepping) (value)
1048 (setf (sap-ref-word (current-thread-sap)
1049 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
1050 (get-lisp-obj-address value)))