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)))
33 ;; %instance-set-conditional can test for 0 (which is a fixnum) and
36 (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
38 (defun release-spinlock (lock offset)
39 (declare (optimize (speed 3) (safety 0)))
40 ;; %instance-set-conditional cannot compare arbitrary objects
42 ;; (sb!vm::%instance-set-conditional lock offset our-value 0)
43 ;; does not work for bignum thread ids.
44 (sb!vm::%instance-set lock offset 0))
46 (defmacro with-spinlock ((queue) &body body)
47 (with-unique-names (pid)
48 `(let ((,pid (current-thread-id)))
51 (get-spinlock ,queue 2 ,pid)
53 (release-spinlock ,queue 2)))))
56 ;;;; the higher-level locking operations are based on waitqueues
58 (declaim (inline waitqueue-data-address mutex-value-address))
61 (name nil :type (or null simple-string))
65 ;;; The bare 4 here and 5 below are offsets of the slots in the struct.
66 ;;; There ought to be some better way to get these numbers
67 (defun waitqueue-data-address (lock)
68 (declare (optimize (speed 3)))
71 (+ (sb!kernel:get-lisp-obj-address lock)
72 (- (* 4 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
74 (defstruct (mutex (:include waitqueue))
77 (defun mutex-value-address (lock)
78 (declare (optimize (speed 3)))
81 (+ (sb!kernel:get-lisp-obj-address lock)
82 (- (* 5 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
84 (declaim (inline futex-wait futex-wake))
85 (sb!alien:define-alien-routine
86 "futex_wait" int (word unsigned-long) (old-value unsigned-long))
87 (sb!alien:define-alien-routine
88 "futex_wake" int (word unsigned-long) (n unsigned-long))
93 (defun get-mutex (lock &optional new-value (wait-p t))
94 "Acquire LOCK, setting it to NEW-VALUE or some suitable default value
95 if NIL. If WAIT-P is non-NIL and the lock is in use, sleep until it
97 (declare (type mutex lock) (optimize (speed 3)))
98 (let ((pid (current-thread-id))
100 (unless new-value (setf new-value pid))
101 (when (eql new-value (mutex-value lock))
102 (warn "recursive lock attempt ~S~%" lock))
105 (setf old (sb!vm::%instance-set-conditional lock 4 nil new-value))
107 (unless wait-p (return nil))
108 (futex-wait (mutex-value-address lock)
109 (sb!kernel:get-lisp-obj-address old)))))
111 (defun release-mutex (lock)
112 (declare (type mutex lock))
113 (setf (mutex-value lock) nil)
114 (futex-wake (mutex-value-address lock) 1))
116 ;;;; condition variables
118 (defun condition-wait (queue lock)
119 "Atomically release LOCK and enqueue ourselves on QUEUE. Another
120 thread may subsequently notify us using CONDITION-NOTIFY, at which
121 time we reacquire LOCK and return to the caller."
123 (let ((value (mutex-value lock)))
125 (let ((me (current-thread-id)))
126 ;; XXX we should do something to ensure that the result of this setf
127 ;; is visible to all CPUs
128 (setf (waitqueue-data queue) me)
130 ;; Now we go to sleep using futex-wait. If anyone else
131 ;; manages to grab LOCK and call CONDITION-NOTIFY during
132 ;; this comment, it will change queue->data, and so
133 ;; futex-wait returns immediately instead of sleeping.
134 ;; Ergo, no lost wakeup
135 (futex-wait (waitqueue-data-address queue)
136 (sb!kernel:get-lisp-obj-address me)))
137 ;; If we are interrupted while waiting, we should do these things
138 ;; before returning. Ideally, in the case of an unhandled signal,
139 ;; we should do them before entering the debugger, but this is
140 ;; better than nothing.
141 (get-mutex lock value))))
144 (defun condition-notify (queue)
145 "Notify one of the processes waiting on QUEUE"
146 (let ((me (current-thread-id)))
147 ;; no problem if >1 thread notifies during the comment in
148 ;; condition-wait: as long as the value in queue-data isn't the
149 ;; waiting thread's id, it matters not what it is
150 ;; XXX we should do something to ensure that the result of this setf
151 ;; is visible to all CPUs
152 (setf (waitqueue-data queue) me)
153 (futex-wake (waitqueue-data-address queue) 1)))
155 (defun condition-broadcast (queue)
156 (let ((me (current-thread-id)))
157 (setf (waitqueue-data queue) me)
158 (futex-wake (waitqueue-data-address queue) (ash 1 30))))
160 (defun make-thread (function)
161 (let* ((real-function (coerce function 'function))
164 (sb!kernel:get-lisp-obj-address
166 ;; in time we'll move some of the binding presently done in C
168 (let ((sb!kernel::*restart-clusters* nil)
169 (sb!kernel::*handler-clusters* nil)
170 (sb!kernel::*condition-restarts* nil)
171 (sb!impl::*descriptor-handlers* nil) ; serve-event
172 (sb!impl::*available-buffers* nil)) ;for fd-stream
173 ;; can't use handling-end-of-the-world, because that flushes
174 ;; output streams, and we don't necessarily have any (or we
175 ;; could be sharing them)
176 (catch 'sb!impl::%end-of-the-world
179 (format nil "~~@<Terminate this thread (~A)~~@:>"
180 (current-thread-id)))
181 ;; now that most things have a chance to work
182 ;; properly without messing up other threads, it's
183 ;; time to enable signals
184 (sb!unix::reset-signal-mask)
185 (funcall real-function))
188 (when (zerop tid) (error "Can't create a new thread"))
189 (with-mutex ((session-lock *session*))
190 (pushnew tid (session-threads *session*)))
193 (defun destroy-thread (thread-id)
194 "Deprecated. Soon to be removed or reimplemented using pthread_cancel."
195 (terminate-thread thread-id))
197 ;;; a moderate degree of care is expected for use of interrupt-thread,
198 ;;; due to its nature: if you interrupt a thread that was holding
199 ;;; important locks then do something that turns out to need those
200 ;;; locks, you probably won't like the effect. Used with thought
201 ;;; though, it's a good deal gentler than the last-resort functions above
203 (define-condition interrupt-thread-error (error)
204 ((thread :reader interrupt-thread-error-thread :initarg :thread)
205 (errno :reader interrupt-thread-error-errno :initarg :errno))
206 (:report (lambda (c s)
207 (format s "interrupt thread ~A failed (~A: ~A)"
208 (interrupt-thread-error-thread c)
209 (interrupt-thread-error-errno c)
210 (strerror (interrupt-thread-error-errno c))))))
212 (defun interrupt-thread (thread function)
213 "Interrupt THREAD and make it run FUNCTION."
214 (let ((function (coerce function 'function)))
215 (multiple-value-bind (res err)
216 (sb!unix::syscall ("interrupt_thread"
217 sb!alien:unsigned-long sb!alien:unsigned-long)
220 (sb!kernel:get-lisp-obj-address function))
222 (error 'interrupt-thread-error :thread thread :errno err)))))
225 (defun terminate-thread (thread-id)
226 "Terminate the thread identified by THREAD-ID, by causing it to run
227 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
228 (interrupt-thread thread-id 'sb!ext:quit))
230 (declaim (inline current-thread-id))
231 (defun current-thread-id ()
233 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
235 ;;;; iterate over the in-memory threads
237 (defun mapcar-threads (function)
238 "Call FUNCTION once for each known thread, giving it the thread structure as argument"
239 (let ((function (coerce function 'function)))
240 (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
241 then (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
242 sb!vm::thread-next-slot))
243 until (sb!sys:sap= thread (sb!sys:int-sap 0))
244 collect (funcall function thread))))
246 (defun thread-sap-from-id (id)
247 (let ((thread (alien-sap (extern-alien "all_threads" (* t)))))
249 (when (sb!sys:sap= thread (sb!sys:int-sap 0)) (return nil))
251 (let ((pid (sb!sys:sap-ref-32 thread (* sb!vm:n-word-bytes
252 sb!vm::thread-os-thread-slot))))
253 (when (= pid id) (return thread))
254 (setf thread (sb!sys:sap-ref-sap thread (* sb!vm:n-word-bytes
255 sb!vm::thread-next-slot)))))))
257 ;;; internal use only. If you think you need to use this, either you
258 ;;; are an SBCL developer, are doing something that you should discuss
259 ;;; with an SBCL developer first, or are doing something that you
260 ;;; should probably discuss with a professional psychiatrist first
261 (defun symbol-value-in-thread (symbol thread-id)
262 (let ((thread (thread-sap-from-id thread-id)))
264 (let* ((index (sb!vm::symbol-tls-index symbol))
265 (tl-val (sb!sys:sap-ref-word thread
266 (* sb!vm:n-word-bytes index))))
267 (if (eql tl-val sb!vm::unbound-marker-widetag)
268 (sb!vm::symbol-global-value symbol)
269 (sb!kernel:make-lisp-obj tl-val))))))
271 ;;;; job control, independent listeners
274 (lock (make-mutex :name "session lock"))
276 (interactive-threads nil)
277 (interactive-threads-queue (make-waitqueue)))
279 (defun new-session ()
280 (let ((tid (current-thread-id)))
281 (make-session :threads (list tid)
282 :interactive-threads (list tid))))
284 (defun init-job-control ()
285 (setf *session* (new-session)))
287 (defun %delete-thread-from-session (tid session)
288 (with-mutex ((session-lock session))
289 (setf (session-threads session)
290 (delete tid (session-threads session))
291 (session-interactive-threads session)
292 (delete tid (session-interactive-threads session)))))
294 (defun call-with-new-session (fn)
295 (%delete-thread-from-session (current-thread-id) *session*)
296 (let ((*session* (new-session))) (funcall fn)))
298 (defmacro with-new-session (args &body forms)
299 (declare (ignore args)) ;for extensibility
300 (sb!int:with-unique-names (fb-name)
301 `(labels ((,fb-name () ,@forms))
302 (call-with-new-session (function ,fb-name)))))
304 ;;; Remove thread id TID from its session, if it has one. This is
305 ;;; called from C mark_thread_dead().
306 (defun handle-thread-exit (tid)
308 (%delete-thread-from-session tid *session*)))
310 (defun terminate-session ()
311 "Kill all threads in session except for this one. Does nothing if current
312 thread is not the foreground thread"
314 ;; FIXME: threads created in other threads may escape termination
315 (let* ((tid (current-thread-id))
317 (with-mutex ((session-lock *session*))
318 (and (eql tid (car (session-interactive-threads *session*)))
319 (session-threads *session*)))))
320 ;; do the kill after dropping the mutex; unwind forms in dying
321 ;; threads may want to do session things
324 ;; terminate the thread but don't be surprised if it has
325 ;; exited in the meantime
326 (handler-case (terminate-thread p)
327 (interrupt-thread-error ()))))))
329 ;;; called from top of invoke-debugger
330 (defun debugger-wait-until-foreground-thread (stream)
331 "Returns T if thread had been running in background, NIL if it was
333 (declare (ignore stream))
335 (with-mutex ((session-lock *session*))
336 (not (member (current-thread-id)
337 (session-interactive-threads *session*))))
341 (defun get-foreground ()
342 (let ((was-foreground t))
344 (with-mutex ((session-lock *session*))
345 (let ((tid (current-thread-id))
346 (int-t (session-interactive-threads *session*)))
347 (when (eql (car int-t) tid)
348 (unless was-foreground
349 (format *query-io* "Resuming thread ~A~%" tid))
350 (return-from get-foreground t))
351 (setf was-foreground nil)
352 (unless (member tid int-t)
353 (setf (cdr (last int-t))
356 (session-interactive-threads-queue *session*)
357 (session-lock *session*)))))))
359 (defun release-foreground (&optional next)
360 "Background this thread. If NEXT is supplied, arrange for it to have the foreground next"
361 (with-mutex ((session-lock *session*))
362 (let ((tid (current-thread-id)))
363 (setf (session-interactive-threads *session*)
364 (delete tid (session-interactive-threads *session*)))
366 (setf (session-interactive-threads *session*)
368 (delete next (session-interactive-threads *session*)))))
369 (condition-broadcast (session-interactive-threads-queue *session*)))))
371 (defun foreground-thread ()
372 (car (session-interactive-threads *session*)))
374 (defun make-listener-thread (tty-name)
375 (assert (probe-file tty-name))
376 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
377 (out (sb!unix:unix-dup in))
378 (err (sb!unix:unix-dup in)))
379 (labels ((thread-repl ()
380 (sb!unix::unix-setsid)
381 (let* ((sb!impl::*stdin*
382 (sb!sys:make-fd-stream in :input t :buffering :line :dual-channel-p t))
384 (sb!sys:make-fd-stream out :output t :buffering :line :dual-channel-p t))
386 (sb!sys:make-fd-stream err :output t :buffering :line :dual-channel-p t))
388 (sb!sys:make-fd-stream err :input t :output t :buffering :line :dual-channel-p t))
389 (sb!impl::*descriptor-handlers* nil))
392 (sb!impl::toplevel-repl nil)
393 (sb!int:flush-standard-output-streams))))))
394 (make-thread #'thread-repl))))