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 ;;; set the doc here because in early-thread FDOCUMENTATION is not
17 (setf (sb!kernel:fdocumentation '*current-thread* 'variable)
18 "Bound in each thread to the thread itself.")
20 (defstruct (thread (:constructor %make-thread))
22 "Thread type. Do not rely on threads being structs as it may change
28 (interruptions-lock (make-mutex :name "thread interruptions lock")))
31 (setf (sb!kernel:fdocumentation 'thread-name 'function)
32 "The name of the thread. Setfable.")
34 (def!method print-object ((thread thread) stream)
35 (if (thread-name thread)
36 (print-unreadable-object (thread stream :type t :identity t)
37 (prin1 (thread-name thread) stream))
38 (print-unreadable-object (thread stream :type t :identity t)
39 ;; body is empty => there is only one space between type and
44 (defun thread-alive-p (thread)
46 "Check if THREAD is running."
47 (thread-%alive-p thread))
49 ;; A thread is eligible for gc iff it has finished and there are no
50 ;; more references to it. This list is supposed to keep a reference to
51 ;; all running threads.
52 (defvar *all-threads* ())
53 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
55 (defun list-all-threads ()
57 "Return a list of the live threads."
58 (with-mutex (*all-threads-lock*)
59 (copy-list *all-threads*)))
61 (declaim (inline current-thread-sap))
62 (defun current-thread-sap ()
63 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
65 (declaim (inline current-thread-sap-id))
66 (defun current-thread-sap-id ()
68 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
70 (defun init-initial-thread ()
71 (let ((initial-thread (%make-thread :name "initial thread"
73 :os-thread (current-thread-sap-id))))
74 (setq *current-thread* initial-thread)
75 ;; Either *all-threads* is empty or it contains exactly one thread
76 ;; in case we are in reinit since saving core with multiple
77 ;; threads doesn't work.
78 (setq *all-threads* (list initial-thread))))
84 ;; FIXME it would be good to define what a thread id is or isn't
85 ;; (our current assumption is that it's a fixnum). It so happens
86 ;; that on Linux it's a pid, but it might not be on posix thread
88 (define-alien-routine ("create_thread" %create-thread)
89 unsigned-long (lisp-fun-address unsigned-long))
91 (define-alien-routine "signal_interrupt_thread"
92 integer (os-thread unsigned-long))
94 (define-alien-routine "block_blockable_signals"
97 (declaim (inline futex-wait futex-wake))
99 (sb!alien:define-alien-routine "futex_wait"
100 int (word unsigned-long) (old-value unsigned-long))
102 (sb!alien:define-alien-routine "futex_wake"
103 int (word unsigned-long) (n unsigned-long)))
105 ;;; used by debug-int.lisp to access interrupt contexts
106 #!-(and sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
108 (defun sb!vm::current-thread-offset-sap (n)
109 (declare (type (unsigned-byte 27) n))
110 (sb!sys:sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
111 (* n sb!vm:n-word-bytes)))
118 (name nil :type (or null simple-string))
121 (declaim (inline get-spinlock release-spinlock))
123 ;;; The bare 2 here and below are offsets of the slots in the struct.
124 ;;; There ought to be some better way to get these numbers
125 (defun get-spinlock (spinlock new-value)
126 (declare (optimize (speed 3) (safety 0))
128 (ignore spinlock new-value))
129 ;; %instance-set-conditional can test for 0 (which is a fixnum) and
133 (eql (sb!vm::%instance-set-conditional spinlock 2 0 new-value) 0)))
135 (defun release-spinlock (spinlock)
136 (declare (optimize (speed 3) (safety 0))
137 #!-sb-thread (ignore spinlock))
138 ;; %instance-set-conditional cannot compare arbitrary objects
140 ;; (sb!vm::%instance-set-conditional spinlock 2 our-value 0)
141 ;; does not work for bignum thread ids.
143 (sb!vm::%instance-set spinlock 2 0))
145 (defmacro with-spinlock ((spinlock) &body body)
146 (sb!int:with-unique-names (lock)
147 `(let ((,lock ,spinlock))
148 (get-spinlock ,lock *current-thread*)
151 (release-spinlock ,lock)))))
158 (name nil :type (or null simple-string))
162 (setf (sb!kernel:fdocumentation 'make-mutex 'function)
164 (sb!kernel:fdocumentation 'mutex-name 'function)
165 "The name of the mutex. Setfable."
166 (sb!kernel:fdocumentation 'mutex-value 'function)
167 "The value of the mutex. NIL if the mutex is free. Setfable.")
170 (declaim (inline mutex-value-address))
172 (defun mutex-value-address (mutex)
173 (declare (optimize (speed 3)))
176 (+ (sb!kernel:get-lisp-obj-address mutex)
177 (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
179 (defun get-mutex (mutex &optional new-value (wait-p t))
181 "Acquire MUTEX, setting it to NEW-VALUE or some suitable default
182 value if NIL. If WAIT-P is non-NIL and the mutex is in use, sleep
183 until it is available"
184 (declare (type mutex mutex) (optimize (speed 3)))
185 (unless new-value (setf new-value *current-thread*))
187 (let ((old-value (mutex-value mutex)))
188 (when (and old-value wait-p)
189 (error "In unithread mode, mutex ~S was requested with WAIT-P ~S and ~
190 new-value ~S, but has already been acquired (with value ~S)."
191 mutex wait-p new-value old-value))
192 (setf (mutex-value mutex) new-value)
196 (when (eql new-value (mutex-value mutex))
197 (warn "recursive lock attempt ~S~%" mutex)
198 (format *debug-io* "Thread: ~A~%" *current-thread*)
199 (sb!debug:backtrace most-positive-fixnum *debug-io*)
200 (force-output *debug-io*))
203 (setf old (sb!vm::%instance-set-conditional mutex 2 nil new-value))
205 (unless wait-p (return nil))
206 (futex-wait (mutex-value-address mutex)
207 (sb!kernel:get-lisp-obj-address old)))))
209 (defun release-mutex (mutex)
211 "Release MUTEX by setting it to NIL. Wake up threads waiting for
213 (declare (type mutex mutex))
214 (setf (mutex-value mutex) nil)
216 (futex-wake (mutex-value-address mutex) 1))
218 ;;;; waitqueues/condition variables
220 (defstruct (waitqueue (:constructor %make-waitqueue))
223 (name nil :type (or null simple-string))
226 (defun make-waitqueue (&key name)
228 "Create a waitqueue."
229 (%make-waitqueue :name name))
232 (setf (sb!kernel:fdocumentation 'waitqueue-name 'function)
233 "The name of the waitqueue. Setfable.")
236 (declaim (inline waitqueue-data-address))
238 (defun waitqueue-data-address (waitqueue)
239 (declare (optimize (speed 3)))
242 (+ (sb!kernel:get-lisp-obj-address waitqueue)
243 (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
245 (defun condition-wait (queue mutex)
247 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
248 thread may subsequently notify us using CONDITION-NOTIFY, at which
249 time we reacquire MUTEX and return to the caller."
250 #!-sb-thread (declare (ignore queue))
252 #!-sb-thread (error "Not supported in unithread builds.")
254 (let ((value (mutex-value mutex)))
256 (let ((me *current-thread*))
257 ;; XXX we should do something to ensure that the result of this setf
258 ;; is visible to all CPUs
259 (setf (waitqueue-data queue) me)
260 (release-mutex mutex)
261 ;; Now we go to sleep using futex-wait. If anyone else
262 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
263 ;; this comment, it will change queue->data, and so
264 ;; futex-wait returns immediately instead of sleeping.
265 ;; Ergo, no lost wakeup
266 (futex-wait (waitqueue-data-address queue)
267 (sb!kernel:get-lisp-obj-address me)))
268 ;; If we are interrupted while waiting, we should do these things
269 ;; before returning. Ideally, in the case of an unhandled signal,
270 ;; we should do them before entering the debugger, but this is
271 ;; better than nothing.
272 (get-mutex mutex value))))
274 (defun condition-notify (queue &optional (n 1))
276 "Notify N threads waiting on QUEUE."
277 #!-sb-thread (declare (ignore queue n))
278 #!-sb-thread (error "Not supported in unithread builds.")
280 (declare (type (and fixnum (integer 1)) n))
282 (let ((me *current-thread*))
283 ;; no problem if >1 thread notifies during the comment in
284 ;; condition-wait: as long as the value in queue-data isn't the
285 ;; waiting thread's id, it matters not what it is
286 ;; XXX we should do something to ensure that the result of this setf
287 ;; is visible to all CPUs
288 (setf (waitqueue-data queue) me)
289 (futex-wake (waitqueue-data-address queue) n)))
291 (defun condition-broadcast (queue)
293 "Notify all threads waiting on QUEUE."
294 (condition-notify queue most-positive-fixnum))
298 (defstruct (semaphore (:constructor %make-semaphore))
301 (name nil :type (or null simple-string))
302 (count 0 :type (integer 0))
304 (queue (make-waitqueue)))
306 (defun make-semaphore (&key name (count 0))
308 "Create a semaphore with the supplied COUNT."
309 (%make-semaphore :name name :count count))
311 (setf (sb!kernel:fdocumentation 'semaphore-name 'function)
312 "The name of the semaphore. Setfable.")
314 (defun wait-on-semaphore (sem)
316 "Decrement the count of SEM if the count would not be negative. Else
317 block until the semaphore can be decremented."
318 ;; a more direct implementation based directly on futexes should be
320 (with-mutex ((semaphore-mutex sem))
321 (loop until (> (semaphore-count sem) 0)
322 do (condition-wait (semaphore-queue sem) (semaphore-mutex sem))
323 finally (decf (semaphore-count sem)))))
325 (defun signal-semaphore (sem &optional (n 1))
327 "Increment the count of SEM by N. If there are threads waiting on
328 this semaphore, then N of them is woken up."
329 (declare (type (and fixnum (integer 1)) n))
330 (with-mutex ((semaphore-mutex sem))
331 (when (= n (incf (semaphore-count sem) n))
332 (condition-notify (semaphore-queue sem) n))))
334 ;;;; job control, independent listeners
337 (lock (make-mutex :name "session lock"))
339 (interactive-threads nil)
340 (interactive-threads-queue (make-waitqueue)))
342 (defvar *session* nil)
344 ;;; the debugger itself tries to acquire the session lock, don't let
345 ;;; funny situations (like getting a sigint while holding the session
347 (defmacro with-session-lock ((session) &body body)
348 #!-sb-thread (declare (ignore session))
352 `(sb!sys:without-interrupts
353 (with-mutex ((session-lock ,session))
356 (defun new-session ()
357 (make-session :threads (list *current-thread*)
358 :interactive-threads (list *current-thread*)))
360 (defun init-job-control ()
361 (setf *session* (new-session)))
363 (defun %delete-thread-from-session (thread session)
364 (with-session-lock (session)
365 (setf (session-threads session)
366 (delete thread (session-threads session))
367 (session-interactive-threads session)
368 (delete thread (session-interactive-threads session)))))
370 (defun call-with-new-session (fn)
371 (%delete-thread-from-session *current-thread* *session*)
372 (let ((*session* (new-session)))
375 (defmacro with-new-session (args &body forms)
376 (declare (ignore args)) ;for extensibility
377 (sb!int:with-unique-names (fb-name)
378 `(labels ((,fb-name () ,@forms))
379 (call-with-new-session (function ,fb-name)))))
381 ;;; Remove thread from its session, if it has one.
383 (defun handle-thread-exit (thread)
384 (with-mutex (*all-threads-lock*)
385 (setq *all-threads* (delete thread *all-threads*)))
387 (%delete-thread-from-session thread *session*)))
389 (defun terminate-session ()
391 "Kill all threads in session except for this one. Does nothing if current
392 thread is not the foreground thread."
393 ;; FIXME: threads created in other threads may escape termination
395 (with-session-lock (*session*)
396 (and (eq *current-thread*
397 (car (session-interactive-threads *session*)))
398 (session-threads *session*)))))
399 ;; do the kill after dropping the mutex; unwind forms in dying
400 ;; threads may want to do session things
401 (dolist (thread to-kill)
402 (unless (eq thread *current-thread*)
403 ;; terminate the thread but don't be surprised if it has
404 ;; exited in the meantime
405 (handler-case (terminate-thread thread)
406 (interrupt-thread-error ()))))))
408 ;;; called from top of invoke-debugger
409 (defun debugger-wait-until-foreground-thread (stream)
410 "Returns T if thread had been running in background, NIL if it was
412 (declare (ignore stream))
416 (with-session-lock (*session*)
417 (not (member *current-thread*
418 (session-interactive-threads *session*))))
421 (defun get-foreground ()
424 (let ((was-foreground t))
426 (with-session-lock (*session*)
427 (let ((int-t (session-interactive-threads *session*)))
428 (when (eq (car int-t) *current-thread*)
429 (unless was-foreground
430 (format *query-io* "Resuming thread ~A~%" *current-thread*))
431 (return-from get-foreground t))
432 (setf was-foreground nil)
433 (unless (member *current-thread* int-t)
434 (setf (cdr (last int-t))
435 (list *current-thread*)))
437 (session-interactive-threads-queue *session*)
438 (session-lock *session*)))))))
440 (defun release-foreground (&optional next)
442 "Background this thread. If NEXT is supplied, arrange for it to
443 have the foreground next."
444 #!-sb-thread (declare (ignore next))
447 (with-session-lock (*session*)
448 (when (rest (session-interactive-threads *session*))
449 (setf (session-interactive-threads *session*)
450 (delete *current-thread* (session-interactive-threads *session*))))
452 (setf (session-interactive-threads *session*)
454 (delete next (session-interactive-threads *session*)))))
455 (condition-broadcast (session-interactive-threads-queue *session*))))
457 (defun foreground-thread ()
458 (car (session-interactive-threads *session*)))
460 (defun make-listener-thread (tty-name)
461 (assert (probe-file tty-name))
462 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
463 (out (sb!unix:unix-dup in))
464 (err (sb!unix:unix-dup in)))
465 (labels ((thread-repl ()
466 (sb!unix::unix-setsid)
467 (let* ((sb!impl::*stdin*
468 (sb!sys:make-fd-stream in :input t :buffering :line
471 (sb!sys:make-fd-stream out :output t :buffering :line
474 (sb!sys:make-fd-stream err :output t :buffering :line
477 (sb!sys:make-fd-stream err :input t :output t
480 (sb!impl::*descriptor-handlers* nil))
483 (sb!impl::toplevel-repl nil)
484 (sb!int:flush-standard-output-streams))))))
485 (make-thread #'thread-repl))))
489 (defun make-thread (function &key name)
491 "Create a new thread of NAME that runs FUNCTION. When the function
492 returns the thread exits."
493 #!-sb-thread (declare (ignore function name))
494 #!-sb-thread (error "Not supported in unithread builds.")
496 (let* ((thread (%make-thread :name name))
497 (setup-sem (make-semaphore :name "Thread setup semaphore"))
498 (real-function (coerce function 'function))
501 ;; in time we'll move some of the binding presently done in C
503 (let ((*current-thread* thread)
504 (sb!kernel::*restart-clusters* nil)
505 (sb!kernel::*handler-clusters* nil)
506 (sb!kernel::*condition-restarts* nil)
507 (sb!impl::*descriptor-handlers* nil)) ; serve-event
508 (setf (thread-os-thread thread) (current-thread-sap-id))
509 (with-mutex (*all-threads-lock*)
510 (push thread *all-threads*))
511 (with-session-lock (*session*)
512 (push thread (session-threads *session*)))
513 (setf (thread-%alive-p thread) t)
514 (signal-semaphore setup-sem)
515 ;; can't use handling-end-of-the-world, because that flushes
516 ;; output streams, and we don't necessarily have any (or we
517 ;; could be sharing them)
518 (catch 'sb!impl::toplevel-catcher
519 (catch 'sb!impl::%end-of-the-world
523 "~~@<Terminate this thread (~A)~~@:>"
527 ;; now that most things have a chance to
528 ;; work properly without messing up other
529 ;; threads, it's time to enable signals
530 (sb!unix::reset-signal-mask)
531 (funcall real-function))
532 ;; we're going down, can't handle
533 ;; interrupts sanely anymore
534 (let ((sb!impl::*gc-inhibit* t))
535 (block-blockable-signals)
536 (setf (thread-%alive-p thread) nil)
537 (setf (thread-os-thread thread) nil)
538 ;; and remove what can be the last
539 ;; reference to this thread
540 (handle-thread-exit thread)))))))
542 (sb!sys:with-pinned-objects (initial-function)
544 ;; don't let the child inherit *CURRENT-THREAD* because that
545 ;; can prevent gc'ing this thread while the child runs
546 (let ((*current-thread* nil))
548 (sb!kernel:get-lisp-obj-address initial-function)))))
549 (when (zerop os-thread)
550 (error "Can't create a new thread"))
551 (wait-on-semaphore setup-sem)
554 (defun destroy-thread (thread)
556 "Deprecated. Same as TERMINATE-THREAD."
557 (terminate-thread thread))
559 (define-condition interrupt-thread-error (error)
560 ((thread :reader interrupt-thread-error-thread :initarg :thread))
562 (:documentation "Interrupting thread failed.")
563 (:report (lambda (c s)
564 (format s "Interrupt thread failed: thread ~A has exited."
565 (interrupt-thread-error-thread c)))))
568 (setf (sb!kernel:fdocumentation 'interrupt-thread-error-thread 'function)
569 "The thread that was not interrupted.")
571 (defmacro with-interruptions-lock ((thread) &body body)
572 `(sb!sys:without-interrupts
573 (with-mutex ((thread-interruptions-lock ,thread))
576 ;; Called from the signal handler.
577 (defun run-interruption ()
578 (let ((interruption (with-interruptions-lock (*current-thread*)
579 (pop (thread-interruptions *current-thread*)))))
580 (funcall interruption)))
582 ;; The order of interrupt execution is peculiar. If thread A
583 ;; interrupts thread B with I1, I2 and B for some reason receives I1
584 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
585 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
586 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
587 ;; just one scenario, and the order of thread interrupt execution is
589 (defun interrupt-thread (thread function)
591 "Interrupt the live THREAD and make it run FUNCTION. A moderate
592 degree of care is expected for use of interrupt-thread, due to its
593 nature: if you interrupt a thread that was holding important locks
594 then do something that turns out to need those locks, you probably
595 won't like the effect."
596 #!-sb-thread (declare (ignore thread))
597 ;; not quite perfect, because it does not take WITHOUT-INTERRUPTS
602 (if (eq thread *current-thread*)
604 (let ((os-thread (thread-os-thread thread)))
605 (cond ((not os-thread)
606 (error 'interrupt-thread-error :thread thread))
608 (with-interruptions-lock (thread)
609 (push function (thread-interruptions thread)))
610 (when (minusp (signal-interrupt-thread os-thread))
611 (error 'interrupt-thread-error :thread thread)))))))
613 (defun terminate-thread (thread)
615 "Terminate the thread identified by THREAD, by causing it to run
616 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
617 (interrupt-thread thread 'sb!ext:quit))
619 ;;; internal use only. If you think you need to use this, either you
620 ;;; are an SBCL developer, are doing something that you should discuss
621 ;;; with an SBCL developer first, or are doing something that you
622 ;;; should probably discuss with a professional psychiatrist first
624 (defun thread-sap-for-id (id)
625 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
627 (when (sb!sys:sap= thread-sap (sb!sys:int-sap 0)) (return nil))
628 (let ((os-thread (sb!sys:sap-ref-word thread-sap
629 (* sb!vm:n-word-bytes
630 sb!vm::thread-os-thread-slot))))
632 (when (= os-thread id) (return thread-sap))
634 (sb!sys:sap-ref-sap thread-sap (* sb!vm:n-word-bytes
635 sb!vm::thread-next-slot)))))))
638 (defun symbol-value-in-thread (symbol thread-sap)
639 (let* ((index (sb!vm::symbol-tls-index symbol))
640 (tl-val (sb!sys:sap-ref-word thread-sap
641 (* sb!vm:n-word-bytes index))))
642 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
643 (sb!vm::symbol-global-value symbol)
644 (sb!kernel:make-lisp-obj tl-val))))