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 (sb!kernel: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")))
36 (setf (sb!kernel:fdocumentation 'thread-name 'function)
37 "The name of the thread. Setfable.")
39 (def!method print-object ((thread thread) stream)
40 (if (thread-name thread)
41 (print-unreadable-object (thread stream :type t :identity t)
42 (prin1 (thread-name thread) stream))
43 (print-unreadable-object (thread stream :type t :identity t)
44 ;; body is empty => there is only one space between type and
49 (defun thread-alive-p (thread)
51 "Check if THREAD is running."
52 (thread-%alive-p thread))
54 ;; A thread is eligible for gc iff it has finished and there are no
55 ;; more references to it. This list is supposed to keep a reference to
56 ;; all running threads.
57 (defvar *all-threads* ())
58 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
60 (defun list-all-threads ()
62 "Return a list of the live threads."
63 (with-mutex (*all-threads-lock*)
64 (copy-list *all-threads*)))
66 (declaim (inline current-thread-sap))
67 (defun current-thread-sap ()
68 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
70 (declaim (inline current-thread-sap-id))
71 (defun current-thread-sap-id ()
73 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
75 (defun init-initial-thread ()
76 (let ((initial-thread (%make-thread :name "initial thread"
78 :os-thread (current-thread-sap-id))))
79 (setq *current-thread* initial-thread)
80 ;; Either *all-threads* is empty or it contains exactly one thread
81 ;; in case we are in reinit since saving core with multiple
82 ;; threads doesn't work.
83 (setq *all-threads* (list initial-thread))))
89 ;; FIXME it would be good to define what a thread id is or isn't
90 ;; (our current assumption is that it's a fixnum). It so happens
91 ;; that on Linux it's a pid, but it might not be on posix thread
93 (define-alien-routine ("create_thread" %create-thread)
94 unsigned-long (lisp-fun-address unsigned-long))
96 (define-alien-routine "signal_interrupt_thread"
97 integer (os-thread unsigned-long))
99 (define-alien-routine "block_blockable_signals"
102 (declaim (inline futex-wait futex-wake))
104 (sb!alien:define-alien-routine "futex_wait"
105 int (word unsigned-long) (old-value unsigned-long))
107 (sb!alien:define-alien-routine "futex_wake"
108 int (word unsigned-long) (n unsigned-long)))
110 ;;; used by debug-int.lisp to access interrupt contexts
111 #!-(and sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
113 (defun sb!vm::current-thread-offset-sap (n)
114 (declare (type (unsigned-byte 27) n))
115 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
116 (* n sb!vm:n-word-bytes)))
120 (declaim (inline get-spinlock release-spinlock))
122 ;;; The bare 2 here and below are offsets of the slots in the struct.
123 ;;; There ought to be some better way to get these numbers
124 (defun get-spinlock (spinlock)
125 (declare (optimize (speed 3) (safety 0))
127 (ignore spinlock new-value))
128 ;; %instance-set-conditional can test for 0 (which is a fixnum) and
132 (eql (sb!vm::%instance-set-conditional spinlock 2 0 1) 0)))
134 (defun release-spinlock (spinlock)
135 (declare (optimize (speed 3) (safety 0))
136 #!-sb-thread (ignore spinlock))
137 ;; %instance-set-conditional cannot compare arbitrary objects
139 ;; (sb!vm::%instance-set-conditional spinlock 2 our-value 0)
140 ;; does not work for bignum thread ids.
142 (sb!vm::%instance-set spinlock 2 0))
144 (defmacro with-spinlock ((spinlock) &body body)
145 (sb!int:with-unique-names (lock)
146 `(let ((,lock ,spinlock))
150 (release-spinlock ,lock)))))
155 (setf (sb!kernel:fdocumentation 'make-mutex 'function)
157 (sb!kernel:fdocumentation 'mutex-name 'function)
158 "The name of the mutex. Setfable."
159 (sb!kernel:fdocumentation 'mutex-value 'function)
160 "The value of the mutex. NIL if the mutex is free. Setfable.")
163 (declaim (inline mutex-value-address))
165 (defun mutex-value-address (mutex)
166 (declare (optimize (speed 3)))
169 (+ (sb!kernel:get-lisp-obj-address mutex)
170 (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
172 (defun get-mutex (mutex &optional (new-value *current-thread*) (wait-p t))
174 "Acquire MUTEX, setting it to NEW-VALUE or some suitable default
175 value if NIL. If WAIT-P is non-NIL and the mutex is in use, sleep
176 until it is available"
177 (declare (type mutex mutex) (optimize (speed 3)))
179 (setq new-value *current-thread*))
181 (let ((old-value (mutex-value mutex)))
182 (when (and old-value wait-p)
183 (error "In unithread mode, mutex ~S was requested with WAIT-P ~S and ~
184 new-value ~S, but has already been acquired (with value ~S)."
185 mutex wait-p new-value old-value))
186 (setf (mutex-value mutex) new-value)
190 (when (eql new-value (mutex-value mutex))
191 (warn "recursive lock attempt ~S~%" mutex)
192 (format *debug-io* "Thread: ~A~%" *current-thread*)
193 (sb!debug:backtrace most-positive-fixnum *debug-io*)
194 (force-output *debug-io*))
197 (setf old (sb!vm::%instance-set-conditional mutex 2 nil new-value))
199 (unless wait-p (return nil))
200 (with-pinned-objects (mutex old)
201 (futex-wait (mutex-value-address mutex)
202 (sb!kernel:get-lisp-obj-address old))))))
204 (defun release-mutex (mutex)
206 "Release MUTEX by setting it to NIL. Wake up threads waiting for
208 (declare (type mutex mutex))
209 (setf (mutex-value mutex) nil)
211 (futex-wake (mutex-value-address mutex) 1))
213 ;;;; waitqueues/condition variables
215 (defstruct (waitqueue (:constructor %make-waitqueue))
218 (name nil :type (or null simple-string))
221 (defun make-waitqueue (&key name)
223 "Create a waitqueue."
224 (%make-waitqueue :name name))
227 (setf (sb!kernel:fdocumentation 'waitqueue-name 'function)
228 "The name of the waitqueue. Setfable.")
231 (declaim (inline waitqueue-data-address))
233 (defun waitqueue-data-address (waitqueue)
234 (declare (optimize (speed 3)))
237 (+ (sb!kernel:get-lisp-obj-address waitqueue)
238 (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
240 (defun condition-wait (queue mutex)
242 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
243 thread may subsequently notify us using CONDITION-NOTIFY, at which
244 time we reacquire MUTEX and return to the caller."
245 #!-sb-thread (declare (ignore queue))
247 #!-sb-thread (error "Not supported in unithread builds.")
249 (let ((value (mutex-value mutex)))
251 (let ((me *current-thread*))
252 ;; XXX we should do something to ensure that the result of this setf
253 ;; is visible to all CPUs
254 (setf (waitqueue-data queue) me)
255 (release-mutex mutex)
256 ;; Now we go to sleep using futex-wait. If anyone else
257 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
258 ;; this comment, it will change queue->data, and so
259 ;; futex-wait returns immediately instead of sleeping.
260 ;; Ergo, no lost wakeup
261 (with-pinned-objects (queue me)
262 (futex-wait (waitqueue-data-address queue)
263 (sb!kernel:get-lisp-obj-address me))))
264 ;; If we are interrupted while waiting, we should do these things
265 ;; before returning. Ideally, in the case of an unhandled signal,
266 ;; we should do them before entering the debugger, but this is
267 ;; better than nothing.
268 (get-mutex mutex value))))
270 (defun condition-notify (queue &optional (n 1))
272 "Notify N threads waiting on QUEUE."
273 #!-sb-thread (declare (ignore queue n))
274 #!-sb-thread (error "Not supported in unithread builds.")
276 (declare (type (and fixnum (integer 1)) n))
278 (let ((me *current-thread*))
279 ;; no problem if >1 thread notifies during the comment in
280 ;; condition-wait: as long as the value in queue-data isn't the
281 ;; waiting thread's id, it matters not what it is
282 ;; XXX we should do something to ensure that the result of this setf
283 ;; is visible to all CPUs
284 (setf (waitqueue-data queue) me)
285 (with-pinned-objects (queue)
286 (futex-wake (waitqueue-data-address queue) n))))
288 (defun condition-broadcast (queue)
290 "Notify all threads waiting on QUEUE."
291 (condition-notify queue most-positive-fixnum))
295 (defstruct (semaphore (:constructor %make-semaphore))
298 (name nil :type (or null simple-string))
299 (count 0 :type (integer 0))
301 (queue (make-waitqueue)))
303 (defun make-semaphore (&key name (count 0))
305 "Create a semaphore with the supplied COUNT."
306 (%make-semaphore :name name :count count))
308 (setf (sb!kernel:fdocumentation 'semaphore-name 'function)
309 "The name of the semaphore. Setfable.")
311 (defun wait-on-semaphore (sem)
313 "Decrement the count of SEM if the count would not be negative. Else
314 block until the semaphore can be decremented."
315 ;; a more direct implementation based directly on futexes should be
317 (with-mutex ((semaphore-mutex sem))
318 (loop until (> (semaphore-count sem) 0)
319 do (condition-wait (semaphore-queue sem) (semaphore-mutex sem))
320 finally (decf (semaphore-count sem)))))
322 (defun signal-semaphore (sem &optional (n 1))
324 "Increment the count of SEM by N. If there are threads waiting on
325 this semaphore, then N of them is woken up."
326 (declare (type (and fixnum (integer 1)) n))
327 (with-mutex ((semaphore-mutex sem))
328 (when (= n (incf (semaphore-count sem) n))
329 (condition-notify (semaphore-queue sem) n))))
331 ;;;; job control, independent listeners
334 (lock (make-mutex :name "session lock"))
336 (interactive-threads nil)
337 (interactive-threads-queue (make-waitqueue)))
339 (defvar *session* nil)
341 ;;; the debugger itself tries to acquire the session lock, don't let
342 ;;; funny situations (like getting a sigint while holding the session
344 (defmacro with-session-lock ((session) &body body)
345 #!-sb-thread (declare (ignore session))
350 (with-mutex ((session-lock ,session))
353 (defun new-session ()
354 (make-session :threads (list *current-thread*)
355 :interactive-threads (list *current-thread*)))
357 (defun init-job-control ()
358 (setf *session* (new-session)))
360 (defun %delete-thread-from-session (thread session)
361 (with-session-lock (session)
362 (setf (session-threads session)
363 (delete thread (session-threads session))
364 (session-interactive-threads session)
365 (delete thread (session-interactive-threads session)))))
367 (defun call-with-new-session (fn)
368 (%delete-thread-from-session *current-thread* *session*)
369 (let ((*session* (new-session)))
372 (defmacro with-new-session (args &body forms)
373 (declare (ignore args)) ;for extensibility
374 (sb!int:with-unique-names (fb-name)
375 `(labels ((,fb-name () ,@forms))
376 (call-with-new-session (function ,fb-name)))))
378 ;;; Remove thread from its session, if it has one.
380 (defun handle-thread-exit (thread)
381 (with-mutex (*all-threads-lock*)
382 (setq *all-threads* (delete thread *all-threads*)))
384 (%delete-thread-from-session thread *session*)))
386 (defun terminate-session ()
388 "Kill all threads in session except for this one. Does nothing if current
389 thread is not the foreground thread."
390 ;; FIXME: threads created in other threads may escape termination
392 (with-session-lock (*session*)
393 (and (eq *current-thread*
394 (car (session-interactive-threads *session*)))
395 (session-threads *session*)))))
396 ;; do the kill after dropping the mutex; unwind forms in dying
397 ;; threads may want to do session things
398 (dolist (thread to-kill)
399 (unless (eq thread *current-thread*)
400 ;; terminate the thread but don't be surprised if it has
401 ;; exited in the meantime
402 (handler-case (terminate-thread thread)
403 (interrupt-thread-error ()))))))
405 ;;; called from top of invoke-debugger
406 (defun debugger-wait-until-foreground-thread (stream)
407 "Returns T if thread had been running in background, NIL if it was
409 (declare (ignore stream))
413 (with-session-lock (*session*)
414 (not (member *current-thread*
415 (session-interactive-threads *session*))))
418 (defun get-foreground ()
421 (let ((was-foreground t))
423 (with-session-lock (*session*)
424 (let ((int-t (session-interactive-threads *session*)))
425 (when (eq (car int-t) *current-thread*)
426 (unless was-foreground
427 (format *query-io* "Resuming thread ~A~%" *current-thread*))
428 (return-from get-foreground t))
429 (setf was-foreground nil)
430 (unless (member *current-thread* int-t)
431 (setf (cdr (last int-t))
432 (list *current-thread*)))
434 (session-interactive-threads-queue *session*)
435 (session-lock *session*)))))))
437 (defun release-foreground (&optional next)
439 "Background this thread. If NEXT is supplied, arrange for it to
440 have the foreground next."
441 #!-sb-thread (declare (ignore next))
444 (with-session-lock (*session*)
445 (when (rest (session-interactive-threads *session*))
446 (setf (session-interactive-threads *session*)
447 (delete *current-thread* (session-interactive-threads *session*))))
449 (setf (session-interactive-threads *session*)
451 (delete next (session-interactive-threads *session*)))))
452 (condition-broadcast (session-interactive-threads-queue *session*))))
454 (defun foreground-thread ()
455 (car (session-interactive-threads *session*)))
457 (defun make-listener-thread (tty-name)
458 (assert (probe-file tty-name))
459 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
460 (out (sb!unix:unix-dup in))
461 (err (sb!unix:unix-dup in)))
462 (labels ((thread-repl ()
463 (sb!unix::unix-setsid)
464 (let* ((sb!impl::*stdin*
465 (make-fd-stream in :input t :buffering :line
468 (make-fd-stream out :output t :buffering :line
471 (make-fd-stream err :output t :buffering :line
474 (make-fd-stream err :input t :output t
477 (sb!impl::*descriptor-handlers* nil))
480 (sb!impl::toplevel-repl nil)
481 (sb!int:flush-standard-output-streams))))))
482 (make-thread #'thread-repl))))
486 (defun make-thread (function &key name)
488 "Create a new thread of NAME that runs FUNCTION. When the function
489 returns the thread exits."
490 #!-sb-thread (declare (ignore function name))
491 #!-sb-thread (error "Not supported in unithread builds.")
493 (let* ((thread (%make-thread :name name))
494 (setup-sem (make-semaphore :name "Thread setup semaphore"))
495 (real-function (coerce function 'function))
498 ;; in time we'll move some of the binding presently done in C
500 (let ((*current-thread* thread)
501 (sb!kernel::*restart-clusters* nil)
502 (sb!kernel::*handler-clusters* nil)
503 (sb!kernel::*condition-restarts* nil)
504 (sb!impl::*descriptor-handlers* nil)) ; serve-event
505 (setf (thread-os-thread thread) (current-thread-sap-id))
506 (with-mutex (*all-threads-lock*)
507 (push thread *all-threads*))
508 (with-session-lock (*session*)
509 (push thread (session-threads *session*)))
510 (setf (thread-%alive-p thread) t)
511 (signal-semaphore setup-sem)
512 ;; can't use handling-end-of-the-world, because that flushes
513 ;; output streams, and we don't necessarily have any (or we
514 ;; could be sharing them)
515 (catch 'sb!impl::toplevel-catcher
516 (catch 'sb!impl::%end-of-the-world
520 "~~@<Terminate this thread (~A)~~@:>"
524 ;; now that most things have a chance to
525 ;; work properly without messing up other
526 ;; threads, it's time to enable signals
527 (sb!unix::reset-signal-mask)
528 (funcall real-function))
529 ;; we're going down, can't handle
530 ;; interrupts sanely anymore
531 (let ((sb!impl::*gc-inhibit* t))
532 (block-blockable-signals)
533 (setf (thread-%alive-p thread) nil)
534 (setf (thread-os-thread thread) nil)
535 ;; and remove what can be the last
536 ;; reference to this thread
537 (handle-thread-exit thread)))))))
539 ;; Keep INITIAL-FUNCTION pinned until the child thread is
540 ;; initialized properly.
541 (with-pinned-objects (initial-function)
544 (sb!kernel:get-lisp-obj-address initial-function))))
545 (when (zerop os-thread)
546 (error "Can't create a new thread"))
547 (wait-on-semaphore setup-sem)
550 (defun destroy-thread (thread)
552 "Deprecated. Same as TERMINATE-THREAD."
553 (terminate-thread thread))
555 (define-condition interrupt-thread-error (error)
556 ((thread :reader interrupt-thread-error-thread :initarg :thread))
558 (:documentation "Interrupting thread failed.")
559 (:report (lambda (c s)
560 (format s "Interrupt thread failed: thread ~A has exited."
561 (interrupt-thread-error-thread c)))))
564 (setf (sb!kernel:fdocumentation 'interrupt-thread-error-thread 'function)
565 "The thread that was not interrupted.")
567 (defmacro with-interruptions-lock ((thread) &body body)
569 (with-mutex ((thread-interruptions-lock ,thread))
572 ;; Called from the signal handler.
573 (defun run-interruption ()
575 (let ((interruption (with-interruptions-lock (*current-thread*)
576 (pop (thread-interruptions *current-thread*)))))
578 (funcall interruption)))))
580 ;; The order of interrupt execution is peculiar. If thread A
581 ;; interrupts thread B with I1, I2 and B for some reason receives I1
582 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
583 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
584 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
585 ;; just one scenario, and the order of thread interrupt execution is
587 (defun interrupt-thread (thread function)
589 "Interrupt the live THREAD and make it run FUNCTION. A moderate
590 degree of care is expected for use of INTERRUPT-THREAD, due to its
591 nature: if you interrupt a thread that was holding important locks
592 then do something that turns out to need those locks, you probably
593 won't like the effect."
594 #!-sb-thread (declare (ignore thread))
595 ;; not quite perfect, because it does not take WITHOUT-INTERRUPTS
600 (if (eq thread *current-thread*)
602 (let ((os-thread (thread-os-thread thread)))
603 (cond ((not os-thread)
604 (error 'interrupt-thread-error :thread thread))
606 (with-interruptions-lock (thread)
607 (push function (thread-interruptions thread)))
608 (when (minusp (signal-interrupt-thread os-thread))
609 (error 'interrupt-thread-error :thread thread)))))))
611 (defun terminate-thread (thread)
613 "Terminate the thread identified by THREAD, by causing it to run
614 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
615 (interrupt-thread thread 'sb!ext:quit))
617 ;;; internal use only. If you think you need to use this, either you
618 ;;; are an SBCL developer, are doing something that you should discuss
619 ;;; with an SBCL developer first, or are doing something that you
620 ;;; should probably discuss with a professional psychiatrist first
622 (defun thread-sap-for-id (id)
623 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
625 (when (sap= thread-sap (int-sap 0)) (return nil))
626 (let ((os-thread (sap-ref-word thread-sap
627 (* sb!vm:n-word-bytes
628 sb!vm::thread-os-thread-slot))))
629 (when (= os-thread id) (return thread-sap))
631 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
632 sb!vm::thread-next-slot)))))))
635 (defun symbol-value-in-thread (symbol thread-sap)
636 (let* ((index (sb!vm::symbol-tls-index symbol))
637 (tl-val (sap-ref-word thread-sap
638 (* sb!vm:n-word-bytes index))))
639 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
640 (sb!vm::symbol-global-value symbol)
641 (sb!kernel:make-lisp-obj tl-val))))