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 ;;; FIXME it would be good to define what a thread id is or isn't (our
15 ;;; current assumption is that it's a fixnum). It so happens that on
16 ;;; Linux it's a pid, but it might not be on posix thread implementations
18 (define-alien-routine ("create_thread" %create-thread)
20 (lisp-fun-address unsigned-long))
22 (define-alien-routine reap-dead-threads void)
24 (defvar *session* nil)
28 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
29 (declaim (inline get-spinlock release-spinlock))
31 (defun get-spinlock (lock offset new-value)
32 (declare (optimize (speed 3) (safety 0)))
34 (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
36 ;; this should do nothing if we didn't own the lock, so safe to use in
37 ;; unwind-protect cleanups when lock acquisition failed for some reason
38 (defun release-spinlock (lock offset our-value)
39 (declare (optimize (speed 3) (safety 0)))
40 (sb!vm::%instance-set-conditional lock offset our-value 0))
42 (defmacro with-spinlock ((queue) &body body)
43 (with-unique-names (pid)
44 `(let ((,pid (current-thread-id)))
47 (get-spinlock ,queue 2 ,pid)
49 (release-spinlock ,queue 2 ,pid)))))
52 ;;;; the higher-level locking operations are based on waitqueues
54 (declaim (inline waitqueue-data-address mutex-value-address))
57 (name nil :type (or null simple-string))
61 ;;; The bare 4 here and 5 below are offsets of the slots in the struct.
62 ;;; There ought to be some better way to get these numbers
63 (defun waitqueue-data-address (lock)
64 (declare (optimize (speed 3)))
67 (+ (sb!kernel:get-lisp-obj-address lock)
68 (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
70 (defstruct (mutex (:include waitqueue))
73 (defun mutex-value-address (lock)
74 (declare (optimize (speed 3)))
77 (+ (sb!kernel:get-lisp-obj-address lock)
78 (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
80 (declaim (inline futex-wait futex-wake))
81 (sb!alien:define-alien-routine
82 "futex_wait" int (word unsigned-long) (old-value unsigned-long))
83 (sb!alien:define-alien-routine
84 "futex_wake" int (word unsigned-long) (n unsigned-long))
89 (defun get-mutex (lock &optional new-value (wait-p t))
90 "Acquire LOCK, setting it to NEW-VALUE or some suitable default value
91 if NIL. If WAIT-P is non-NIL and the lock is in use, sleep until it
93 (declare (type mutex lock) (optimize (speed 3)))
94 (let ((pid (current-thread-id))
96 (unless new-value (setf new-value pid))
97 (when (eql new-value (mutex-value lock))
98 (warn "recursive lock attempt ~S~%" lock))
101 (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
103 (unless wait-p (return nil))
104 (futex-wait (mutex-value-address lock)
105 (sb!kernel:get-lisp-obj-address old)))))
107 (defun release-mutex (lock)
108 (declare (type mutex lock))
109 (setf (mutex-value lock) nil)
110 (futex-wake (mutex-value-address lock) 1))
112 ;;;; condition variables
114 (defun condition-wait (queue lock)
115 "Atomically release LOCK and enqueue ourselves on QUEUE. Another
116 thread may subsequently notify us using CONDITION-NOTIFY, at which
117 time we reacquire LOCK and return to the caller."
119 (let ((value (mutex-value lock)))
121 (let ((me (current-thread-id)))
122 ;; XXX we should do something to ensure that the result of this setf
123 ;; is visible to all CPUs
124 (setf (waitqueue-data queue) me)
126 ;; Now we go to sleep using futex-wait. If anyone else
127 ;; manages to grab LOCK and call CONDITION-NOTIFY during
128 ;; this comment, it will change queue->data, and so
129 ;; futex-wait returns immediately instead of sleeping.
130 ;; Ergo, no lost wakeup
131 (futex-wait (waitqueue-data-address queue)
132 (sb!kernel:get-lisp-obj-address me)))
133 ;; If we are interrupted while waiting, we should do these things
134 ;; before returning. Ideally, in the case of an unhandled signal,
135 ;; we should do them before entering the debugger, but this is
136 ;; better than nothing.
137 (get-mutex lock value))))
140 (defun condition-notify (queue)
141 "Notify one of the processes waiting on QUEUE"
142 (let ((me (current-thread-id)))
143 ;; no problem if >1 thread notifies during the comment in
144 ;; condition-wait: as long as the value in queue-data isn't the
145 ;; waiting thread's id, it matters not what it is
146 ;; XXX we should do something to ensure that the result of this setf
147 ;; is visible to all CPUs
148 (setf (waitqueue-data queue) me)
149 (futex-wake (waitqueue-data-address queue) 1)))
151 (defun condition-broadcast (queue)
152 (let ((me (current-thread-id)))
153 (setf (waitqueue-data queue) me)
154 (futex-wake (waitqueue-data-address queue) (ash 1 30))))
156 (defun make-thread (function)
157 (let* ((real-function (coerce function 'function))
160 (sb!kernel:get-lisp-obj-address
162 ;; in time we'll move some of the binding presently done in C
164 (let ((sb!kernel::*restart-clusters* nil)
165 (sb!kernel::*handler-clusters* nil)
166 (sb!kernel::*condition-restarts* nil)
167 (sb!impl::*descriptor-handlers* nil) ; serve-event
168 (sb!impl::*available-buffers* nil)) ;for fd-stream
169 ;; can't use handling-end-of-the-world, because that flushes
170 ;; output streams, and we don't necessarily have any (or we
171 ;; could be sharing them)
172 (catch 'sb!impl::%end-of-the-world
175 (format nil "~~@<Terminate this thread (~A)~~@:>"
176 (current-thread-id)))
177 ;; now that most things have a chance to work
178 ;; properly without messing up other threads, it's
179 ;; time to enable signals
180 (sb!unix::reset-signal-mask)
181 (funcall real-function))
184 (when (zerop tid) (error "Can't create a new thread"))
185 (with-mutex ((session-lock *session*))
186 (pushnew tid (session-threads *session*)))
189 (defun destroy-thread (thread-id)
190 "Deprecated. Soon to be removed or reimplemented using pthread_cancel."
191 (terminate-thread thread-id))
193 ;;; a moderate degree of care is expected for use of interrupt-thread,
194 ;;; due to its nature: if you interrupt a thread that was holding
195 ;;; important locks then do something that turns out to need those
196 ;;; locks, you probably won't like the effect. Used with thought
197 ;;; though, it's a good deal gentler than the last-resort functions above
199 (define-condition interrupt-thread-error (error)
200 ((thread :reader interrupt-thread-error-thread :initarg :thread)
201 (errno :reader interrupt-thread-error-errno :initarg :errno))
202 (:report (lambda (c s)
203 (format s "interrupt thread ~A failed (~A: ~A)"
204 (interrupt-thread-error-thread c)
205 (interrupt-thread-error-errno c)
206 (strerror (interrupt-thread-error-errno c))))))
208 (defun interrupt-thread (thread function)
209 "Interrupt THREAD and make it run FUNCTION."
210 (let ((function (coerce function 'function)))
211 (multiple-value-bind (res err)
212 (sb!unix::syscall ("interrupt_thread"
213 sb!alien:unsigned-long sb!alien:unsigned-long)
216 (sb!kernel:get-lisp-obj-address function))
218 (error 'interrupt-thread-error :thread thread :errno err)))))
221 (defun terminate-thread (thread-id)
222 "Terminate the thread identified by THREAD-ID, by causing it to run
223 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
224 (interrupt-thread thread-id 'sb!ext:quit))
226 (declaim (inline current-thread-id))
227 (defun current-thread-id ()
229 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
231 ;;;; iterate over the in-memory threads
233 (defun mapcar-threads (function)
234 "Call FUNCTION once for each known thread, giving it the thread structure as argument"
235 (let ((function (coerce function 'function)))
236 (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
237 then (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
238 sb!vm::thread-next-slot))
239 until (sb!sys:sap= thread (sb!sys:int-sap 0))
240 collect (funcall function thread))))
242 (defun thread-sap-from-id (id)
243 (let ((thread (alien-sap (extern-alien "all_threads" (* t)))))
245 (when (sb!sys:sap= thread (sb!sys:int-sap 0)) (return nil))
247 (let ((pid (sb!sys:sap-ref-32 thread (* sb!vm:n-word-bytes
248 sb!vm::thread-os-thread-slot))))
249 (when (= pid id) (return thread))
250 (setf thread (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
251 sb!vm::thread-next-slot)))))))
253 ;;; internal use only. If you think you need to use this, either you
254 ;;; are an SBCL developer, are doing something that you should discuss
255 ;;; with an SBCL developer first, or are doing something that you
256 ;;; should probably discuss with a professional psychiatrist first
257 (defun symbol-value-in-thread (symbol thread-id)
258 (let ((thread (thread-sap-from-id thread-id)))
260 (let* ((index (sb!vm::symbol-tls-index symbol))
261 (tl-val (sb!sys:sap-ref-word thread
262 (* sb!vm:n-word-bytes index))))
263 (if (eql tl-val sb!vm::unbound-marker-widetag)
264 (sb!vm::symbol-global-value symbol)
265 (sb!kernel:make-lisp-obj tl-val))))))
267 ;;;; job control, independent listeners
270 (lock (make-mutex :name "session lock"))
272 (interactive-threads nil)
273 (interactive-threads-queue (make-waitqueue)))
275 (defun new-session ()
276 (let ((tid (current-thread-id)))
277 (make-session :threads (list tid)
278 :interactive-threads (list tid))))
280 (defun init-job-control ()
281 (setf *session* (new-session)))
283 (defun %delete-thread-from-session (tid session)
284 (with-mutex ((session-lock session))
285 (setf (session-threads session)
286 (delete tid (session-threads session))
287 (session-interactive-threads session)
288 (delete tid (session-interactive-threads session)))))
290 (defun call-with-new-session (fn)
291 (%delete-thread-from-session (current-thread-id) *session*)
292 (let ((*session* (new-session))) (funcall fn)))
294 (defmacro with-new-session (args &body forms)
295 (declare (ignore args)) ;for extensibility
296 (sb!int:with-unique-names (fb-name)
297 `(labels ((,fb-name () ,@forms))
298 (call-with-new-session (function ,fb-name)))))
300 ;;; Remove thread id TID from its session, if it has one. This is
301 ;;; called from C mark_thread_dead().
302 (defun handle-thread-exit (tid)
304 (%delete-thread-from-session tid *session*)))
306 (defun terminate-session ()
307 "Kill all threads in session except for this one. Does nothing if current
308 thread is not the foreground thread"
310 ;; FIXME: threads created in other threads may escape termination
311 (let* ((tid (current-thread-id))
313 (with-mutex ((session-lock *session*))
314 (and (eql tid (car (session-interactive-threads *session*)))
315 (session-threads *session*)))))
316 ;; do the kill after dropping the mutex; unwind forms in dying
317 ;; threads may want to do session things
320 ;; terminate the thread but don't be surprised if it has
321 ;; exited in the meantime
322 (handler-case (terminate-thread p)
323 (interrupt-thread-error ()))))))
325 ;;; called from top of invoke-debugger
326 (defun debugger-wait-until-foreground-thread (stream)
327 "Returns T if thread had been running in background, NIL if it was
329 (declare (ignore stream))
331 (with-mutex ((session-lock *session*))
332 (not (member (current-thread-id)
333 (session-interactive-threads *session*))))
337 (defun get-foreground ()
338 (let ((was-foreground t))
340 (with-mutex ((session-lock *session*))
341 (let ((tid (current-thread-id))
342 (int-t (session-interactive-threads *session*)))
343 (when (eql (car int-t) tid)
344 (unless was-foreground
345 (format *query-io* "Resuming thread ~A~%" tid))
346 (return-from get-foreground t))
347 (setf was-foreground nil)
348 (unless (member tid int-t)
349 (setf (cdr (last int-t))
352 (session-interactive-threads-queue *session*)
353 (session-lock *session*)))))))
355 (defun release-foreground (&optional next)
356 "Background this thread. If NEXT is supplied, arrange for it to have the foreground next"
357 (with-mutex ((session-lock *session*))
358 (let ((tid (current-thread-id)))
359 (setf (session-interactive-threads *session*)
360 (delete tid (session-interactive-threads *session*)))
362 (setf (session-interactive-threads *session*)
364 (delete next (session-interactive-threads *session*)))))
365 (condition-broadcast (session-interactive-threads-queue *session*)))))
367 (defun foreground-thread ()
368 (car (session-interactive-threads *session*)))
370 (defun make-listener-thread (tty-name)
371 (assert (probe-file tty-name))
372 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
373 (out (sb!unix:unix-dup in))
374 (err (sb!unix:unix-dup in)))
375 (labels ((thread-repl ()
376 (sb!unix::unix-setsid)
377 (let* ((sb!impl::*stdin*
378 (sb!sys:make-fd-stream in :input t :buffering :line :dual-channel-p t))
380 (sb!sys:make-fd-stream out :output t :buffering :line :dual-channel-p t))
382 (sb!sys:make-fd-stream err :output t :buffering :line :dual-channel-p t))
384 (sb!sys:make-fd-stream err :input t :output t :buffering :line :dual-channel-p t))
385 (sb!impl::*descriptor-handlers* nil))
388 (sb!impl::toplevel-repl nil)
389 (sb!int:flush-standard-output-streams))))))
390 (make-thread #'thread-repl))))