1.0.22.22: (SETF FIND-CLASSOID) to drop DEFTYPE lambda-lists and source-locations
[sbcl/tcr.git] / src / code / target-thread.lisp
blobc534ca01fb2e94e0b61973ecc1322602059ac56a
1 ;;;; support for threads in the target machine
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
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
20 ;;; available, yet
21 #!+sb-doc
22 (setf (fdocumentation '*current-thread* 'variable)
23 "Bound in each thread to the thread itself.")
25 (defstruct (thread (:constructor %make-thread))
26 #!+sb-doc
27 "Thread type. Do not rely on threads being structs as it may change
28 in future versions."
29 name
30 %alive-p
31 os-thread
32 interruptions
33 (interruptions-lock (make-mutex :name "thread interruptions lock"))
34 result
35 (result-lock (make-mutex :name "thread result lock")))
37 #!+sb-doc
38 (setf (fdocumentation 'thread-name 'function)
39 "The name of the thread. Setfable.")
41 (def!method print-object ((thread thread) stream)
42 (print-unreadable-object (thread stream :type t :identity t)
43 (let* ((cookie (list thread))
44 (info (if (thread-alive-p thread)
45 :running
46 (multiple-value-list (join-thread thread :default cookie))))
47 (state (if (eq :running info)
48 info
49 (if (eq cookie (car info))
50 :aborted
51 :finished)))
52 (values (when (eq :finished state) info)))
53 (format stream "~@[~S ~]~:[~A~;~A~:[ no values~; values: ~:*~{~S~^, ~}~]~]"
54 (thread-name thread)
55 (eq :finished state)
56 state
57 values))))
59 (defun thread-alive-p (thread)
60 #!+sb-doc
61 "Check if THREAD is running."
62 (thread-%alive-p thread))
64 ;; A thread is eligible for gc iff it has finished and there are no
65 ;; more references to it. This list is supposed to keep a reference to
66 ;; all running threads.
67 (defvar *all-threads* ())
68 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
70 (defvar *default-alloc-signal* nil)
72 (defmacro with-all-threads-lock (&body body)
73 `(with-system-mutex (*all-threads-lock*)
74 ,@body))
76 (defun list-all-threads ()
77 #!+sb-doc
78 "Return a list of the live threads."
79 (with-all-threads-lock
80 (copy-list *all-threads*)))
82 (declaim (inline current-thread-sap))
83 (defun current-thread-sap ()
84 (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
86 (declaim (inline current-thread-os-thread))
87 (defun current-thread-os-thread ()
88 (sap-int
89 (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
91 (defun init-initial-thread ()
92 (/show0 "Entering INIT-INITIAL-THREAD")
93 (let ((initial-thread (%make-thread :name "initial thread"
94 :%alive-p t
95 :os-thread (current-thread-os-thread))))
96 (setq *current-thread* initial-thread)
97 ;; Either *all-threads* is empty or it contains exactly one thread
98 ;; in case we are in reinit since saving core with multiple
99 ;; threads doesn't work.
100 (setq *all-threads* (list initial-thread))))
102 ;;;;
104 #!+sb-thread
105 (progn
106 ;; FIXME it would be good to define what a thread id is or isn't
107 ;; (our current assumption is that it's a fixnum). It so happens
108 ;; that on Linux it's a pid, but it might not be on posix thread
109 ;; implementations.
110 (define-alien-routine ("create_thread" %create-thread)
111 unsigned-long (lisp-fun-address unsigned-long))
113 (define-alien-routine "signal_interrupt_thread"
114 integer (os-thread unsigned-long))
116 (define-alien-routine "block_deferrable_signals"
117 void)
119 #!+sb-lutex
120 (progn
121 (declaim (inline %lutex-init %lutex-wait %lutex-wake
122 %lutex-lock %lutex-unlock))
124 (define-alien-routine ("lutex_init" %lutex-init)
125 int (lutex unsigned-long))
127 (define-alien-routine ("lutex_wait" %lutex-wait)
128 int (queue-lutex unsigned-long) (mutex-lutex unsigned-long))
130 (define-alien-routine ("lutex_wake" %lutex-wake)
131 int (lutex unsigned-long) (n int))
133 (define-alien-routine ("lutex_lock" %lutex-lock)
134 int (lutex unsigned-long))
136 (define-alien-routine ("lutex_trylock" %lutex-trylock)
137 int (lutex unsigned-long))
139 (define-alien-routine ("lutex_unlock" %lutex-unlock)
140 int (lutex unsigned-long))
142 (define-alien-routine ("lutex_destroy" %lutex-destroy)
143 int (lutex unsigned-long))
145 ;; FIXME: Defining a whole bunch of alien-type machinery just for
146 ;; passing primitive lutex objects directly to foreign functions
147 ;; doesn't seem like fun right now. So instead we just manually
148 ;; pin the lutex, get its address, and let the callee untag it.
149 (defmacro with-lutex-address ((name lutex) &body body)
150 `(let ((,name ,lutex))
151 (with-pinned-objects (,name)
152 (let ((,name (get-lisp-obj-address ,name)))
153 ,@body))))
155 (defun make-lutex ()
156 (/show0 "Entering MAKE-LUTEX")
157 ;; Suppress GC until the lutex has been properly registered with
158 ;; the GC.
159 (without-gcing
160 (let ((lutex (sb!vm::%make-lutex)))
161 (/show0 "LUTEX=..")
162 (/hexstr lutex)
163 (with-lutex-address (lutex lutex)
164 (%lutex-init lutex))
165 lutex))))
167 #!-sb-lutex
168 (progn
169 (declaim (inline futex-wait %futex-wait futex-wake))
171 (define-alien-routine ("futex_wait" %futex-wait)
172 int (word unsigned-long) (old-value unsigned-long)
173 (to-sec long) (to-usec unsigned-long))
175 (defun futex-wait (word old to-sec to-usec)
176 (with-interrupts
177 (%futex-wait word old to-sec to-usec)))
179 (define-alien-routine "futex_wake"
180 int (word unsigned-long) (n unsigned-long))))
182 ;;; used by debug-int.lisp to access interrupt contexts
183 #!-(or sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
184 #!-sb-thread
185 (defun sb!vm::current-thread-offset-sap (n)
186 (declare (type (unsigned-byte 27) n))
187 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
188 (* n sb!vm:n-word-bytes)))
190 #!+sb-thread
191 (defun sb!vm::current-thread-offset-sap (n)
192 (declare (type (unsigned-byte 27) n))
193 (sb!vm::current-thread-offset-sap n))
195 (declaim (inline get-spinlock release-spinlock))
197 ;; Should always be called with interrupts disabled.
198 (defun get-spinlock (spinlock)
199 (declare (optimize (speed 3) (safety 0)))
200 (let* ((new *current-thread*)
201 (old (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)))
202 (when old
203 (when (eq old new)
204 (error "Recursive lock attempt on ~S." spinlock))
205 #!+sb-thread
206 (flet ((cas ()
207 (if (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
208 (thread-yield)
209 (return-from get-spinlock t))))
210 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
211 ;; If interrupts are enabled, but we are allowed to enabled them,
212 ;; check for pending interrupts every once in a while.
213 (loop
214 (loop repeat 128 do (cas)) ; 128 is arbitrary here
215 (sb!unix::%check-interrupts))
216 (loop (cas)))))
219 (defun release-spinlock (spinlock)
220 (declare (optimize (speed 3) (safety 0)))
221 (setf (spinlock-value spinlock) nil)
222 nil)
224 ;;;; mutexes
226 #!+sb-doc
227 (setf (fdocumentation 'make-mutex 'function)
228 "Create a mutex."
229 (fdocumentation 'mutex-name 'function)
230 "The name of the mutex. Setfable.")
232 #!+(and sb-thread (not sb-lutex))
233 (progn
234 (define-structure-slot-addressor mutex-state-address
235 :structure mutex
236 :slot state)
237 ;; Important: current code assumes these are fixnums or other
238 ;; lisp objects that don't need pinning.
239 (defconstant +lock-free+ 0)
240 (defconstant +lock-taken+ 1)
241 (defconstant +lock-contested+ 2))
243 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
244 #!+sb-doc
245 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
246 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
247 non-NIL and the mutex is in use, sleep until it is available.
249 Note: using GET-MUTEX to assign a MUTEX to another thread then the
250 current one is not recommended, and liable to be deprecated.
252 GET-MUTEX is not interrupt safe. The correct way to call it is:
254 (WITHOUT-INTERRUPTS
256 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
257 ...)
259 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
260 call while the mutex is in an inconsistent state while
261 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
263 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
264 directly."
265 (declare (type mutex mutex) (optimize (speed 3))
266 #!-sb-thread (ignore waitp))
267 (unless new-owner
268 (setq new-owner *current-thread*))
269 (when (eql new-owner (mutex-%owner mutex))
270 (error "Recursive lock attempt ~S." mutex))
271 #!+sb-thread
272 (progn
273 ;; FIXME: Lutexes do not currently support deadlines, as at least
274 ;; on Darwin pthread_foo_timedbar functions are not supported:
275 ;; this means that we probably need to use the Carbon multiprocessing
276 ;; functions on Darwin.
278 ;; FIXME: This is definitely not interrupt safe: what happens if
279 ;; we get hit (1) during the lutex calls (ok, they may be safe,
280 ;; but has that been checked?) (2) after the lutex call, but
281 ;; before setting the mutex owner.
282 #!+sb-lutex
283 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
284 (if waitp
285 (with-interrupts (%lutex-lock lutex))
286 (%lutex-trylock lutex))))
287 (setf (mutex-%owner mutex) new-owner)
289 #!-sb-lutex
290 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
291 +lock-free+
292 +lock-taken+)))
293 (unless (or (eql +lock-free+ old) (not waitp))
294 (tagbody
295 :retry
296 (when (or (eql +lock-contested+ old)
297 (not (eql +lock-free+
298 (sb!ext:compare-and-swap (mutex-state mutex)
299 +lock-taken+
300 +lock-contested+))))
301 ;; Wait on the contested lock.
302 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
303 (when (= 1 (with-pinned-objects (mutex)
304 (futex-wait (mutex-state-address mutex)
305 (get-lisp-obj-address +lock-contested+)
306 (or to-sec -1)
307 (or to-usec 0))))
308 (signal-deadline))))
309 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
310 +lock-free+
311 +lock-contested+))
312 ;; Did we get it?
313 (unless (eql +lock-free+ old)
314 (go :retry))))
315 (cond ((eql +lock-free+ old)
316 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
317 nil new-owner)))
318 (when prev
319 (bug "Old owner in free mutex: ~S" prev))
321 (waitp
322 (bug "Failed to acquire lock with WAITP."))))))
324 (defun release-mutex (mutex)
325 #!+sb-doc
326 "Release MUTEX by setting it to NIL. Wake up threads waiting for
327 this mutex.
329 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
330 around calls to it.
332 Signals a WARNING is current thread is not the current owner of the
333 mutex."
334 (declare (type mutex mutex))
335 ;; Order matters: set owner to NIL before releasing state.
336 (let* ((self *current-thread*)
337 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
338 (unless (eql self old-owner)
339 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
340 (setf (mutex-%owner mutex) nil)))
341 #!+sb-thread
342 (progn
343 #!+sb-lutex
344 (with-lutex-address (lutex (mutex-lutex mutex))
345 (%lutex-unlock lutex))
346 #!-sb-lutex
347 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
348 +lock-taken+ +lock-free+)))
349 (when (eql old +lock-contested+)
350 (sb!ext:compare-and-swap (mutex-state mutex)
351 +lock-contested+ +lock-free+)
352 (with-pinned-objects (mutex)
353 (futex-wake (mutex-state-address mutex) 1))))
354 nil))
356 ;;;; waitqueues/condition variables
358 (defstruct (waitqueue (:constructor %make-waitqueue))
359 #!+sb-doc
360 "Waitqueue type."
361 (name nil :type (or null simple-string))
362 #!+(and sb-lutex sb-thread)
363 (lutex (make-lutex))
364 #!-sb-lutex
365 (data nil))
367 (defun make-waitqueue (&key name)
368 #!+sb-doc
369 "Create a waitqueue."
370 (%make-waitqueue :name name))
372 #!+sb-doc
373 (setf (fdocumentation 'waitqueue-name 'function)
374 "The name of the waitqueue. Setfable.")
376 #!+(and sb-thread (not sb-lutex))
377 (define-structure-slot-addressor waitqueue-data-address
378 :structure waitqueue
379 :slot data)
381 (defun condition-wait (queue mutex)
382 #!+sb-doc
383 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
384 thread may subsequently notify us using CONDITION-NOTIFY, at which
385 time we reacquire MUTEX and return to the caller."
386 #!-sb-thread (declare (ignore queue))
387 (assert mutex)
388 #!-sb-thread (error "Not supported in unithread builds.")
389 #!+sb-thread
390 (let ((me *current-thread*))
391 (assert (eq me (mutex-%owner mutex)))
392 (/show0 "CONDITION-WAITing")
393 #!+sb-lutex
394 ;; Need to disable interrupts so that we don't miss setting the owner on
395 ;; our way out. (pthread_cond_wait handles the actual re-acquisition.)
396 (without-interrupts
397 (unwind-protect
398 (progn
399 (setf (mutex-%owner mutex) nil)
400 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
401 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
402 (with-local-interrupts
403 (%lutex-wait queue-lutex-address mutex-lutex-address)))))
404 (setf (mutex-%owner mutex) me)))
405 #!-sb-lutex
406 ;; Need to disable interrupts so that we don't miss grabbing the mutex
407 ;; on our way out.
408 (without-interrupts
409 (unwind-protect
410 (let ((me *current-thread*))
411 ;; FIXME: should we do something to ensure that the result
412 ;; of this setf is visible to all CPUs?
413 (setf (waitqueue-data queue) me)
414 (release-mutex mutex)
415 ;; Now we go to sleep using futex-wait. If anyone else
416 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
417 ;; this comment, it will change queue->data, and so
418 ;; futex-wait returns immediately instead of sleeping.
419 ;; Ergo, no lost wakeup. We may get spurious wakeups,
420 ;; but that's ok.
421 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
422 (when (= 1 (with-pinned-objects (queue me)
423 (allow-with-interrupts
424 (futex-wait (waitqueue-data-address queue)
425 (get-lisp-obj-address me)
426 (or to-sec -1) ;; our way if saying "no timeout"
427 (or to-usec 0)))))
428 (signal-deadline))))
429 ;; If we are interrupted while waiting, we should do these things
430 ;; before returning. Ideally, in the case of an unhandled signal,
431 ;; we should do them before entering the debugger, but this is
432 ;; better than nothing.
433 (get-mutex mutex)))))
435 (defun condition-notify (queue &optional (n 1))
436 #!+sb-doc
437 "Notify N threads waiting on QUEUE."
438 #!-sb-thread (declare (ignore queue n))
439 #!-sb-thread (error "Not supported in unithread builds.")
440 #!+sb-thread
441 (declare (type (and fixnum (integer 1)) n))
442 (/show0 "Entering CONDITION-NOTIFY")
443 #!+sb-thread
444 (progn
445 #!+sb-lutex
446 (with-lutex-address (lutex (waitqueue-lutex queue))
447 (%lutex-wake lutex n))
448 ;; no problem if >1 thread notifies during the comment in
449 ;; condition-wait: as long as the value in queue-data isn't the
450 ;; waiting thread's id, it matters not what it is
451 ;; XXX we should do something to ensure that the result of this setf
452 ;; is visible to all CPUs
453 #!-sb-lutex
454 (let ((me *current-thread*))
455 (progn
456 (setf (waitqueue-data queue) me)
457 (with-pinned-objects (queue)
458 (futex-wake (waitqueue-data-address queue) n))))))
460 (defun condition-broadcast (queue)
461 #!+sb-doc
462 "Notify all threads waiting on QUEUE."
463 (condition-notify queue
464 ;; On a 64-bit platform truncating M-P-F to an int results
465 ;; in -1, which wakes up only one thread.
466 (ldb (byte 29 0)
467 most-positive-fixnum)))
469 ;;;; semaphores
471 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
472 #!+sb-doc
473 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
474 should be considered an implementation detail, and may change in the
475 future."
476 (name nil :type (or null simple-string))
477 (%count 0 :type (integer 0))
478 (waitcount 0 :type (integer 0))
479 (mutex (make-mutex))
480 (queue (make-waitqueue)))
482 (setf (fdocumentation 'semaphore-name 'function)
483 "The name of the semaphore INSTANCE. Setfable.")
485 (declaim (inline semaphore-count))
486 (defun semaphore-count (instance)
487 "Returns the current count of the semaphore INSTANCE."
488 (semaphore-%count instance))
490 (defun make-semaphore (&key name (count 0))
491 #!+sb-doc
492 "Create a semaphore with the supplied COUNT and NAME."
493 (%make-semaphore name count))
495 (defun wait-on-semaphore (semaphore)
496 #!+sb-doc
497 "Decrement the count of SEMAPHORE if the count would not be
498 negative. Else blocks until the semaphore can be decremented."
499 ;; A more direct implementation based directly on futexes should be
500 ;; possible.
502 ;; We need to disable interrupts so that we don't forget to decrement the
503 ;; waitcount (which would happen if an asynch interrupt should catch us on
504 ;; our way out from the loop.)
505 (with-system-mutex ((semaphore-mutex semaphore) :allow-with-interrupts t)
506 ;; Quick check: is it positive? If not, enter the wait loop.
507 (let ((count (semaphore-%count semaphore)))
508 (if (plusp count)
509 (setf (semaphore-%count semaphore) (1- count))
510 (unwind-protect
511 (progn
512 (incf (semaphore-waitcount semaphore))
513 (loop until (plusp (setf count (semaphore-%count semaphore)))
514 do (condition-wait (semaphore-queue semaphore) (semaphore-mutex semaphore)))
515 (setf (semaphore-%count semaphore) (1- count)))
516 (decf (semaphore-waitcount semaphore)))))))
518 (defun signal-semaphore (semaphore &optional (n 1))
519 #!+sb-doc
520 "Increment the count of SEMAPHORE by N. If there are threads waiting
521 on this semaphore, then N of them is woken up."
522 (declare (type (integer 1) n))
523 ;; Need to disable interrupts so that we don't lose a wakeup after we have
524 ;; incremented the count.
525 (with-system-mutex ((semaphore-mutex semaphore))
526 (let ((waitcount (semaphore-waitcount semaphore))
527 (count (incf (semaphore-%count semaphore) n)))
528 (when (plusp waitcount)
529 (condition-notify (semaphore-queue semaphore) (min waitcount count))))))
531 ;;;; job control, independent listeners
533 (defstruct session
534 (lock (make-mutex :name "session lock"))
535 (threads nil)
536 (interactive-threads nil)
537 (interactive-threads-queue (make-waitqueue)))
539 (defvar *session* nil)
541 ;;; The debugger itself tries to acquire the session lock, don't let
542 ;;; funny situations (like getting a sigint while holding the session
543 ;;; lock) occur. At the same time we need to allow interrupts while
544 ;;; *waiting* for the session lock for things like GET-FOREGROUND
545 ;;; to be interruptible.
547 ;;; Take care: we sometimes need to obtain the session lock while holding
548 ;;; on to *ALL-THREADS-LOCK*, so we must _never_ obtain it _after_ getting
549 ;;; a session lock! (Deadlock risk.)
551 ;;; FIXME: It would be good to have ordered locks to ensure invariants like
552 ;;; the above.
553 (defmacro with-session-lock ((session) &body body)
554 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
555 ,@body))
557 (defun new-session ()
558 (make-session :threads (list *current-thread*)
559 :interactive-threads (list *current-thread*)))
561 (defun init-job-control ()
562 (/show0 "Entering INIT-JOB-CONTROL")
563 (setf *session* (new-session))
564 (/show0 "Exiting INIT-JOB-CONTROL"))
566 (defun %delete-thread-from-session (thread session)
567 (with-session-lock (session)
568 (setf (session-threads session)
569 (delete thread (session-threads session))
570 (session-interactive-threads session)
571 (delete thread (session-interactive-threads session)))))
573 (defun call-with-new-session (fn)
574 (%delete-thread-from-session *current-thread* *session*)
575 (let ((*session* (new-session)))
576 (funcall fn)))
578 (defmacro with-new-session (args &body forms)
579 (declare (ignore args)) ;for extensibility
580 (sb!int:with-unique-names (fb-name)
581 `(labels ((,fb-name () ,@forms))
582 (call-with-new-session (function ,fb-name)))))
584 ;;; Remove thread from its session, if it has one.
585 #!+sb-thread
586 (defun handle-thread-exit (thread)
587 (/show0 "HANDLING THREAD EXIT")
588 ;; We're going down, can't handle interrupts sanely anymore.
589 ;; GC remains enabled.
590 (block-deferrable-signals)
591 ;; Lisp-side cleanup
592 (with-all-threads-lock
593 (setf (thread-%alive-p thread) nil)
594 (setf (thread-os-thread thread) nil)
595 (setq *all-threads* (delete thread *all-threads*))
596 (when *session*
597 (%delete-thread-from-session thread *session*)))
598 #!+sb-lutex
599 (without-gcing
600 (/show0 "FREEING MUTEX LUTEX")
601 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
602 (%lutex-destroy lutex))))
604 (defun terminate-session ()
605 #!+sb-doc
606 "Kill all threads in session except for this one. Does nothing if current
607 thread is not the foreground thread."
608 ;; FIXME: threads created in other threads may escape termination
609 (let ((to-kill
610 (with-session-lock (*session*)
611 (and (eq *current-thread*
612 (car (session-interactive-threads *session*)))
613 (session-threads *session*)))))
614 ;; do the kill after dropping the mutex; unwind forms in dying
615 ;; threads may want to do session things
616 (dolist (thread to-kill)
617 (unless (eq thread *current-thread*)
618 ;; terminate the thread but don't be surprised if it has
619 ;; exited in the meantime
620 (handler-case (terminate-thread thread)
621 (interrupt-thread-error ()))))))
623 ;;; called from top of invoke-debugger
624 (defun debugger-wait-until-foreground-thread (stream)
625 "Returns T if thread had been running in background, NIL if it was
626 interactive."
627 (declare (ignore stream))
628 #!-sb-thread nil
629 #!+sb-thread
630 (prog1
631 (with-session-lock (*session*)
632 (not (member *current-thread*
633 (session-interactive-threads *session*))))
634 (get-foreground)))
636 (defun get-foreground ()
637 #!-sb-thread t
638 #!+sb-thread
639 (let ((was-foreground t))
640 (loop
641 (/show0 "Looping in GET-FOREGROUND")
642 (with-session-lock (*session*)
643 (let ((int-t (session-interactive-threads *session*)))
644 (when (eq (car int-t) *current-thread*)
645 (unless was-foreground
646 (format *query-io* "Resuming thread ~A~%" *current-thread*))
647 (return-from get-foreground t))
648 (setf was-foreground nil)
649 (unless (member *current-thread* int-t)
650 (setf (cdr (last int-t))
651 (list *current-thread*)))
652 (condition-wait
653 (session-interactive-threads-queue *session*)
654 (session-lock *session*)))))))
656 (defun release-foreground (&optional next)
657 #!+sb-doc
658 "Background this thread. If NEXT is supplied, arrange for it to
659 have the foreground next."
660 #!-sb-thread (declare (ignore next))
661 #!-sb-thread nil
662 #!+sb-thread
663 (with-session-lock (*session*)
664 (when (rest (session-interactive-threads *session*))
665 (setf (session-interactive-threads *session*)
666 (delete *current-thread* (session-interactive-threads *session*))))
667 (when next
668 (setf (session-interactive-threads *session*)
669 (list* next
670 (delete next (session-interactive-threads *session*)))))
671 (condition-broadcast (session-interactive-threads-queue *session*))))
673 (defun foreground-thread ()
674 (car (session-interactive-threads *session*)))
676 (defun make-listener-thread (tty-name)
677 (assert (probe-file tty-name))
678 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
679 (out (sb!unix:unix-dup in))
680 (err (sb!unix:unix-dup in)))
681 (labels ((thread-repl ()
682 (sb!unix::unix-setsid)
683 (let* ((sb!impl::*stdin*
684 (make-fd-stream in :input t :buffering :line
685 :dual-channel-p t))
686 (sb!impl::*stdout*
687 (make-fd-stream out :output t :buffering :line
688 :dual-channel-p t))
689 (sb!impl::*stderr*
690 (make-fd-stream err :output t :buffering :line
691 :dual-channel-p t))
692 (sb!impl::*tty*
693 (make-fd-stream err :input t :output t
694 :buffering :line
695 :dual-channel-p t))
696 (sb!impl::*descriptor-handlers* nil))
697 (with-new-session ()
698 (unwind-protect
699 (sb!impl::toplevel-repl nil)
700 (sb!int:flush-standard-output-streams))))))
701 (make-thread #'thread-repl))))
703 ;;;; the beef
705 (defun make-thread (function &key name)
706 #!+sb-doc
707 "Create a new thread of NAME that runs FUNCTION. When the function
708 returns the thread exits. The return values of FUNCTION are kept
709 around and can be retrieved by JOIN-THREAD."
710 #!-sb-thread (declare (ignore function name))
711 #!-sb-thread (error "Not supported in unithread builds.")
712 #!+sb-thread
713 (let* ((thread (%make-thread :name name))
714 (setup-sem (make-semaphore :name "Thread setup semaphore"))
715 (real-function (coerce function 'function))
716 (initial-function
717 (lambda ()
718 ;; In time we'll move some of the binding presently done in C
719 ;; here too.
721 ;; KLUDGE: Here we have a magic list of variables that are
722 ;; not thread-safe for one reason or another. As people
723 ;; report problems with the thread safety of certain
724 ;; variables, (e.g. "*print-case* in multiple threads
725 ;; broken", sbcl-devel 2006-07-14), we add a few more
726 ;; bindings here. The Right Thing is probably some variant
727 ;; of Allegro's *cl-default-special-bindings*, as that is at
728 ;; least accessible to users to secure their own libraries.
729 ;; --njf, 2006-07-15
730 (let* ((*current-thread* thread)
731 (*restart-clusters* nil)
732 (*handler-clusters* (sb!kernel::initial-handler-clusters))
733 (*condition-restarts* nil)
734 (sb!impl::*deadline* nil)
735 (sb!impl::*step-out* nil)
736 ;; internal printer variables
737 (sb!impl::*previous-case* nil)
738 (sb!impl::*previous-readtable-case* nil)
739 (empty (vector))
740 (sb!impl::*merge-sort-temp-vector* empty)
741 (sb!impl::*zap-array-data-temp* empty)
742 (sb!impl::*internal-symbol-output-fun* nil)
743 (sb!impl::*descriptor-handlers* nil)) ; serve-event
744 ;; Binding from C
745 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
746 (setf (thread-os-thread thread) (current-thread-os-thread))
747 (with-mutex ((thread-result-lock thread))
748 (with-all-threads-lock
749 (push thread *all-threads*))
750 (with-session-lock (*session*)
751 (push thread (session-threads *session*)))
752 (setf (thread-%alive-p thread) t)
753 (signal-semaphore setup-sem)
754 ;; can't use handling-end-of-the-world, because that flushes
755 ;; output streams, and we don't necessarily have any (or we
756 ;; could be sharing them)
757 (catch 'sb!impl::toplevel-catcher
758 (catch 'sb!impl::%end-of-the-world
759 (with-simple-restart
760 (terminate-thread
761 (format nil
762 "~~@<Terminate this thread (~A)~~@:>"
763 *current-thread*))
764 (unwind-protect
765 (progn
766 ;; now that most things have a chance to
767 ;; work properly without messing up other
768 ;; threads, it's time to enable signals
769 (sb!unix::reset-signal-mask)
770 (setf (thread-result thread)
771 (cons t
772 (multiple-value-list
773 (funcall real-function)))))
774 (handle-thread-exit thread)))))))
775 (values))))
776 ;; Keep INITIAL-FUNCTION pinned until the child thread is
777 ;; initialized properly.
778 (with-pinned-objects (initial-function)
779 (let ((os-thread
780 (%create-thread
781 (get-lisp-obj-address initial-function))))
782 (when (zerop os-thread)
783 (error "Can't create a new thread"))
784 (wait-on-semaphore setup-sem)
785 thread))))
787 (define-condition join-thread-error (error)
788 ((thread :reader join-thread-error-thread :initarg :thread))
789 #!+sb-doc
790 (:documentation "Joining thread failed.")
791 (:report (lambda (c s)
792 (format s "Joining thread failed: thread ~A ~
793 has not returned normally."
794 (join-thread-error-thread c)))))
796 #!+sb-doc
797 (setf (fdocumentation 'join-thread-error-thread 'function)
798 "The thread that we failed to join.")
800 (defun join-thread (thread &key (default nil defaultp))
801 #!+sb-doc
802 "Suspend current thread until THREAD exits. Returns the result
803 values of the thread function. If the thread does not exit normally,
804 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
805 (with-mutex ((thread-result-lock thread))
806 (cond ((car (thread-result thread))
807 (values-list (cdr (thread-result thread))))
808 (defaultp
809 default)
811 (error 'join-thread-error :thread thread)))))
813 (defun destroy-thread (thread)
814 #!+sb-doc
815 "Deprecated. Same as TERMINATE-THREAD."
816 (terminate-thread thread))
818 (define-condition interrupt-thread-error (error)
819 ((thread :reader interrupt-thread-error-thread :initarg :thread))
820 #!+sb-doc
821 (:documentation "Interrupting thread failed.")
822 (:report (lambda (c s)
823 (format s "Interrupt thread failed: thread ~A has exited."
824 (interrupt-thread-error-thread c)))))
826 #!+sb-doc
827 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
828 "The thread that was not interrupted.")
830 (defmacro with-interruptions-lock ((thread) &body body)
831 `(with-system-mutex ((thread-interruptions-lock ,thread))
832 ,@body))
834 ;; Called from the signal handler in C.
835 (defun run-interruption ()
836 (in-interruption ()
837 (loop
838 (let ((interruption (with-interruptions-lock (*current-thread*)
839 (pop (thread-interruptions *current-thread*)))))
840 (if interruption
841 (with-interrupts
842 (funcall interruption))
843 (return))))))
845 ;; The order of interrupt execution is peculiar. If thread A
846 ;; interrupts thread B with I1, I2 and B for some reason receives I1
847 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
848 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
849 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
850 ;; just one scenario, and the order of thread interrupt execution is
851 ;; undefined.
852 (defun interrupt-thread (thread function)
853 #!+sb-doc
854 "Interrupt the live THREAD and make it run FUNCTION. A moderate
855 degree of care is expected for use of INTERRUPT-THREAD, due to its
856 nature: if you interrupt a thread that was holding important locks
857 then do something that turns out to need those locks, you probably
858 won't like the effect."
859 #!-sb-thread (declare (ignore thread))
860 #!-sb-thread
861 (with-interrupt-bindings
862 (with-interrupts (funcall function)))
863 #!+sb-thread
864 (if (eq thread *current-thread*)
865 (with-interrupt-bindings
866 (with-interrupts (funcall function)))
867 (let ((os-thread (thread-os-thread thread)))
868 (cond ((not os-thread)
869 (error 'interrupt-thread-error :thread thread))
871 (with-interruptions-lock (thread)
872 (push function (thread-interruptions thread)))
873 (when (minusp (signal-interrupt-thread os-thread))
874 (error 'interrupt-thread-error :thread thread)))))))
876 (defun terminate-thread (thread)
877 #!+sb-doc
878 "Terminate the thread identified by THREAD, by causing it to run
879 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
880 (interrupt-thread thread 'sb!ext:quit))
882 (define-alien-routine "thread_yield" int)
884 #!+sb-doc
885 (setf (fdocumentation 'thread-yield 'function)
886 "Yield the processor to other threads.")
888 ;;; internal use only. If you think you need to use these, either you
889 ;;; are an SBCL developer, are doing something that you should discuss
890 ;;; with an SBCL developer first, or are doing something that you
891 ;;; should probably discuss with a professional psychiatrist first
892 #!+sb-thread
893 (progn
894 (defun %thread-sap (thread)
895 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
896 (target (thread-os-thread thread)))
897 (loop
898 (when (sap= thread-sap (int-sap 0)) (return nil))
899 (let ((os-thread (sap-ref-word thread-sap
900 (* sb!vm:n-word-bytes
901 sb!vm::thread-os-thread-slot))))
902 (when (= os-thread target) (return thread-sap))
903 (setf thread-sap
904 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
905 sb!vm::thread-next-slot)))))))
907 (defun %symbol-value-in-thread (symbol thread)
908 (tagbody
909 ;; Prevent the dead from dying completely while we look for the TLS area...
910 (with-all-threads-lock
911 (if (thread-alive-p thread)
912 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
913 (tl-val (sap-ref-word (%thread-sap thread) offset)))
914 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
915 (go :unbound)
916 (return-from %symbol-value-in-thread (values (make-lisp-obj tl-val) t))))
917 (return-from %symbol-value-in-thread (values nil nil))))
918 :unbound
919 (error "Cannot read thread-local symbol value: ~S unbound in ~S" symbol thread)))
921 (defun %set-symbol-value-in-thread (symbol thread value)
922 (tagbody
923 (with-pinned-objects (value)
924 ;; Prevent the dead from dying completely while we look for the TLS area...
925 (with-all-threads-lock
926 (if (thread-alive-p thread)
927 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
928 (sap (%thread-sap thread))
929 (tl-val (sap-ref-word sap offset)))
930 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
931 (go :unbound)
932 (setf (sap-ref-word sap offset) (get-lisp-obj-address value)))
933 (return-from %set-symbol-value-in-thread (values value t)))
934 (return-from %set-symbol-value-in-thread (values nil nil)))))
935 :unbound
936 (error "Cannot set thread-local symbol value: ~S unbound in ~S" symbol thread))))
938 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
939 (sb!vm::locked-symbol-global-value-add symbol-name delta))
941 ;;; Stepping
943 (defun thread-stepping ()
944 (make-lisp-obj
945 (sap-ref-word (current-thread-sap)
946 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
948 (defun (setf thread-stepping) (value)
949 (setf (sap-ref-word (current-thread-sap)
950 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
951 (get-lisp-obj-address value)))