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 (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 *current-thread*) (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)))
186 (setq new-value *current-thread*))
188 (let ((old-value (mutex-value mutex)))
189 (when (and old-value wait-p)
190 (error "In unithread mode, mutex ~S was requested with WAIT-P ~S and ~
191 new-value ~S, but has already been acquired (with value ~S)."
192 mutex wait-p new-value old-value))
193 (setf (mutex-value mutex) new-value)
197 (when (eql new-value (mutex-value mutex))
198 (warn "recursive lock attempt ~S~%" mutex)
199 (format *debug-io* "Thread: ~A~%" *current-thread*)
200 (sb!debug:backtrace most-positive-fixnum *debug-io*)
201 (force-output *debug-io*))
204 (setf old (sb!vm::%instance-set-conditional mutex 2 nil new-value))
206 (unless wait-p (return nil))
207 (futex-wait (mutex-value-address mutex)
208 (sb!kernel:get-lisp-obj-address old)))))
210 (defun release-mutex (mutex)
212 "Release MUTEX by setting it to NIL. Wake up threads waiting for
214 (declare (type mutex mutex))
215 (setf (mutex-value mutex) nil)
217 (futex-wake (mutex-value-address mutex) 1))
219 ;;;; waitqueues/condition variables
221 (defstruct (waitqueue (:constructor %make-waitqueue))
224 (name nil :type (or null simple-string))
227 (defun make-waitqueue (&key name)
229 "Create a waitqueue."
230 (%make-waitqueue :name name))
233 (setf (sb!kernel:fdocumentation 'waitqueue-name 'function)
234 "The name of the waitqueue. Setfable.")
237 (declaim (inline waitqueue-data-address))
239 (defun waitqueue-data-address (waitqueue)
240 (declare (optimize (speed 3)))
243 (+ (sb!kernel:get-lisp-obj-address waitqueue)
244 (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
246 (defun condition-wait (queue mutex)
248 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
249 thread may subsequently notify us using CONDITION-NOTIFY, at which
250 time we reacquire MUTEX and return to the caller."
251 #!-sb-thread (declare (ignore queue))
253 #!-sb-thread (error "Not supported in unithread builds.")
255 (let ((value (mutex-value mutex)))
257 (let ((me *current-thread*))
258 ;; XXX we should do something to ensure that the result of this setf
259 ;; is visible to all CPUs
260 (setf (waitqueue-data queue) me)
261 (release-mutex mutex)
262 ;; Now we go to sleep using futex-wait. If anyone else
263 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
264 ;; this comment, it will change queue->data, and so
265 ;; futex-wait returns immediately instead of sleeping.
266 ;; Ergo, no lost wakeup
267 (futex-wait (waitqueue-data-address queue)
268 (sb!kernel:get-lisp-obj-address me)))
269 ;; If we are interrupted while waiting, we should do these things
270 ;; before returning. Ideally, in the case of an unhandled signal,
271 ;; we should do them before entering the debugger, but this is
272 ;; better than nothing.
273 (get-mutex mutex value))))
275 (defun condition-notify (queue &optional (n 1))
277 "Notify N threads waiting on QUEUE."
278 #!-sb-thread (declare (ignore queue n))
279 #!-sb-thread (error "Not supported in unithread builds.")
281 (declare (type (and fixnum (integer 1)) n))
283 (let ((me *current-thread*))
284 ;; no problem if >1 thread notifies during the comment in
285 ;; condition-wait: as long as the value in queue-data isn't the
286 ;; waiting thread's id, it matters not what it is
287 ;; XXX we should do something to ensure that the result of this setf
288 ;; is visible to all CPUs
289 (setf (waitqueue-data queue) me)
290 (futex-wake (waitqueue-data-address queue) n)))
292 (defun condition-broadcast (queue)
294 "Notify all threads waiting on QUEUE."
295 (condition-notify queue most-positive-fixnum))
299 (defstruct (semaphore (:constructor %make-semaphore))
302 (name nil :type (or null simple-string))
303 (count 0 :type (integer 0))
305 (queue (make-waitqueue)))
307 (defun make-semaphore (&key name (count 0))
309 "Create a semaphore with the supplied COUNT."
310 (%make-semaphore :name name :count count))
312 (setf (sb!kernel:fdocumentation 'semaphore-name 'function)
313 "The name of the semaphore. Setfable.")
315 (defun wait-on-semaphore (sem)
317 "Decrement the count of SEM if the count would not be negative. Else
318 block until the semaphore can be decremented."
319 ;; a more direct implementation based directly on futexes should be
321 (with-mutex ((semaphore-mutex sem))
322 (loop until (> (semaphore-count sem) 0)
323 do (condition-wait (semaphore-queue sem) (semaphore-mutex sem))
324 finally (decf (semaphore-count sem)))))
326 (defun signal-semaphore (sem &optional (n 1))
328 "Increment the count of SEM by N. If there are threads waiting on
329 this semaphore, then N of them is woken up."
330 (declare (type (and fixnum (integer 1)) n))
331 (with-mutex ((semaphore-mutex sem))
332 (when (= n (incf (semaphore-count sem) n))
333 (condition-notify (semaphore-queue sem) n))))
335 ;;;; job control, independent listeners
338 (lock (make-mutex :name "session lock"))
340 (interactive-threads nil)
341 (interactive-threads-queue (make-waitqueue)))
343 (defvar *session* nil)
345 ;;; the debugger itself tries to acquire the session lock, don't let
346 ;;; funny situations (like getting a sigint while holding the session
348 (defmacro with-session-lock ((session) &body body)
349 #!-sb-thread (declare (ignore session))
354 (with-mutex ((session-lock ,session))
357 (defun new-session ()
358 (make-session :threads (list *current-thread*)
359 :interactive-threads (list *current-thread*)))
361 (defun init-job-control ()
362 (setf *session* (new-session)))
364 (defun %delete-thread-from-session (thread session)
365 (with-session-lock (session)
366 (setf (session-threads session)
367 (delete thread (session-threads session))
368 (session-interactive-threads session)
369 (delete thread (session-interactive-threads session)))))
371 (defun call-with-new-session (fn)
372 (%delete-thread-from-session *current-thread* *session*)
373 (let ((*session* (new-session)))
376 (defmacro with-new-session (args &body forms)
377 (declare (ignore args)) ;for extensibility
378 (sb!int:with-unique-names (fb-name)
379 `(labels ((,fb-name () ,@forms))
380 (call-with-new-session (function ,fb-name)))))
382 ;;; Remove thread from its session, if it has one.
384 (defun handle-thread-exit (thread)
385 (with-mutex (*all-threads-lock*)
386 (setq *all-threads* (delete thread *all-threads*)))
388 (%delete-thread-from-session thread *session*)))
390 (defun terminate-session ()
392 "Kill all threads in session except for this one. Does nothing if current
393 thread is not the foreground thread."
394 ;; FIXME: threads created in other threads may escape termination
396 (with-session-lock (*session*)
397 (and (eq *current-thread*
398 (car (session-interactive-threads *session*)))
399 (session-threads *session*)))))
400 ;; do the kill after dropping the mutex; unwind forms in dying
401 ;; threads may want to do session things
402 (dolist (thread to-kill)
403 (unless (eq thread *current-thread*)
404 ;; terminate the thread but don't be surprised if it has
405 ;; exited in the meantime
406 (handler-case (terminate-thread thread)
407 (interrupt-thread-error ()))))))
409 ;;; called from top of invoke-debugger
410 (defun debugger-wait-until-foreground-thread (stream)
411 "Returns T if thread had been running in background, NIL if it was
413 (declare (ignore stream))
417 (with-session-lock (*session*)
418 (not (member *current-thread*
419 (session-interactive-threads *session*))))
422 (defun get-foreground ()
425 (let ((was-foreground t))
427 (with-session-lock (*session*)
428 (let ((int-t (session-interactive-threads *session*)))
429 (when (eq (car int-t) *current-thread*)
430 (unless was-foreground
431 (format *query-io* "Resuming thread ~A~%" *current-thread*))
432 (return-from get-foreground t))
433 (setf was-foreground nil)
434 (unless (member *current-thread* int-t)
435 (setf (cdr (last int-t))
436 (list *current-thread*)))
438 (session-interactive-threads-queue *session*)
439 (session-lock *session*)))))))
441 (defun release-foreground (&optional next)
443 "Background this thread. If NEXT is supplied, arrange for it to
444 have the foreground next."
445 #!-sb-thread (declare (ignore next))
448 (with-session-lock (*session*)
449 (when (rest (session-interactive-threads *session*))
450 (setf (session-interactive-threads *session*)
451 (delete *current-thread* (session-interactive-threads *session*))))
453 (setf (session-interactive-threads *session*)
455 (delete next (session-interactive-threads *session*)))))
456 (condition-broadcast (session-interactive-threads-queue *session*))))
458 (defun foreground-thread ()
459 (car (session-interactive-threads *session*)))
461 (defun make-listener-thread (tty-name)
462 (assert (probe-file tty-name))
463 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
464 (out (sb!unix:unix-dup in))
465 (err (sb!unix:unix-dup in)))
466 (labels ((thread-repl ()
467 (sb!unix::unix-setsid)
468 (let* ((sb!impl::*stdin*
469 (make-fd-stream in :input t :buffering :line
472 (make-fd-stream out :output t :buffering :line
475 (make-fd-stream err :output t :buffering :line
478 (make-fd-stream err :input t :output t
481 (sb!impl::*descriptor-handlers* nil))
484 (sb!impl::toplevel-repl nil)
485 (sb!int:flush-standard-output-streams))))))
486 (make-thread #'thread-repl))))
490 (defun make-thread (function &key name)
492 "Create a new thread of NAME that runs FUNCTION. When the function
493 returns the thread exits."
494 #!-sb-thread (declare (ignore function name))
495 #!-sb-thread (error "Not supported in unithread builds.")
497 (let* ((thread (%make-thread :name name))
498 (setup-sem (make-semaphore :name "Thread setup semaphore"))
499 (real-function (coerce function 'function))
502 ;; in time we'll move some of the binding presently done in C
504 (let ((*current-thread* thread)
505 (sb!kernel::*restart-clusters* nil)
506 (sb!kernel::*handler-clusters* nil)
507 (sb!kernel::*condition-restarts* nil)
508 (sb!impl::*descriptor-handlers* nil)) ; serve-event
509 (setf (thread-os-thread thread) (current-thread-sap-id))
510 (with-mutex (*all-threads-lock*)
511 (push thread *all-threads*))
512 (with-session-lock (*session*)
513 (push thread (session-threads *session*)))
514 (setf (thread-%alive-p thread) t)
515 (signal-semaphore setup-sem)
516 ;; can't use handling-end-of-the-world, because that flushes
517 ;; output streams, and we don't necessarily have any (or we
518 ;; could be sharing them)
519 (catch 'sb!impl::toplevel-catcher
520 (catch 'sb!impl::%end-of-the-world
524 "~~@<Terminate this thread (~A)~~@:>"
528 ;; now that most things have a chance to
529 ;; work properly without messing up other
530 ;; threads, it's time to enable signals
531 (sb!unix::reset-signal-mask)
532 (funcall real-function))
533 ;; we're going down, can't handle
534 ;; interrupts sanely anymore
535 (let ((sb!impl::*gc-inhibit* t))
536 (block-blockable-signals)
537 (setf (thread-%alive-p thread) nil)
538 (setf (thread-os-thread thread) nil)
539 ;; and remove what can be the last
540 ;; reference to this thread
541 (handle-thread-exit thread)))))))
543 (with-pinned-objects (initial-function)
545 ;; don't let the child inherit *CURRENT-THREAD* because that
546 ;; can prevent gc'ing this thread while the child runs
547 (let ((*current-thread* nil))
549 (sb!kernel:get-lisp-obj-address initial-function)))))
550 (when (zerop os-thread)
551 (error "Can't create a new thread"))
552 (wait-on-semaphore setup-sem)
555 (defun destroy-thread (thread)
557 "Deprecated. Same as TERMINATE-THREAD."
558 (terminate-thread thread))
560 (define-condition interrupt-thread-error (error)
561 ((thread :reader interrupt-thread-error-thread :initarg :thread))
563 (:documentation "Interrupting thread failed.")
564 (:report (lambda (c s)
565 (format s "Interrupt thread failed: thread ~A has exited."
566 (interrupt-thread-error-thread c)))))
569 (setf (sb!kernel:fdocumentation 'interrupt-thread-error-thread 'function)
570 "The thread that was not interrupted.")
572 (defmacro with-interruptions-lock ((thread) &body body)
574 (with-mutex ((thread-interruptions-lock ,thread))
577 ;; Called from the signal handler.
578 (defun run-interruption ()
580 (let ((interruption (with-interruptions-lock (*current-thread*)
581 (pop (thread-interruptions *current-thread*)))))
583 (funcall interruption)))))
585 ;; The order of interrupt execution is peculiar. If thread A
586 ;; interrupts thread B with I1, I2 and B for some reason receives I1
587 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
588 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
589 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
590 ;; just one scenario, and the order of thread interrupt execution is
592 (defun interrupt-thread (thread function)
594 "Interrupt the live THREAD and make it run FUNCTION. A moderate
595 degree of care is expected for use of INTERRUPT-THREAD, due to its
596 nature: if you interrupt a thread that was holding important locks
597 then do something that turns out to need those locks, you probably
598 won't like the effect."
599 #!-sb-thread (declare (ignore thread))
600 ;; not quite perfect, because it does not take WITHOUT-INTERRUPTS
605 (if (eq thread *current-thread*)
607 (let ((os-thread (thread-os-thread thread)))
608 (cond ((not os-thread)
609 (error 'interrupt-thread-error :thread thread))
611 (with-interruptions-lock (thread)
612 (push function (thread-interruptions thread)))
613 (when (minusp (signal-interrupt-thread os-thread))
614 (error 'interrupt-thread-error :thread thread)))))))
616 (defun terminate-thread (thread)
618 "Terminate the thread identified by THREAD, by causing it to run
619 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
620 (interrupt-thread thread 'sb!ext:quit))
622 ;;; internal use only. If you think you need to use this, either you
623 ;;; are an SBCL developer, are doing something that you should discuss
624 ;;; with an SBCL developer first, or are doing something that you
625 ;;; should probably discuss with a professional psychiatrist first
627 (defun thread-sap-for-id (id)
628 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
630 (when (sap= thread-sap (int-sap 0)) (return nil))
631 (let ((os-thread (sap-ref-word thread-sap
632 (* sb!vm:n-word-bytes
633 sb!vm::thread-os-thread-slot))))
634 (when (= os-thread id) (return thread-sap))
636 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
637 sb!vm::thread-next-slot)))))))
640 (defun symbol-value-in-thread (symbol thread-sap)
641 (let* ((index (sb!vm::symbol-tls-index symbol))
642 (tl-val (sap-ref-word thread-sap
643 (* sb!vm:n-word-bytes index))))
644 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
645 (sb!vm::symbol-global-value symbol)
646 (sb!kernel:make-lisp-obj tl-val))))