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 (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"))
35 (result-lock (make-mutex :name
"thread result lock")))
38 (setf (fdocumentation 'thread-name
'function
)
39 "The name of the thread. Setfable.")
41 (def!method print-object
((thread thread
) stream
)
42 (if (thread-name thread
)
43 (print-unreadable-object (thread stream
:type t
:identity t
)
44 (prin1 (thread-name thread
) stream
))
45 (print-unreadable-object (thread stream
:type t
:identity t
)
46 ;; body is empty => there is only one space between type and
51 (defun thread-alive-p (thread)
53 "Check if THREAD is running."
54 (thread-%alive-p thread
))
56 ;; A thread is eligible for gc iff it has finished and there are no
57 ;; more references to it. This list is supposed to keep a reference to
58 ;; all running threads.
59 (defvar *all-threads
* ())
60 (defvar *all-threads-lock
* (make-mutex :name
"all threads lock"))
62 (defmacro with-all-threads-lock
(&body body
)
63 `(call-with-system-mutex (lambda () ,@body
) *all-threads-lock
*))
65 (defun list-all-threads ()
67 "Return a list of the live threads."
68 (with-all-threads-lock
69 (copy-list *all-threads
*)))
71 (declaim (inline current-thread-sap
))
72 (defun current-thread-sap ()
73 (sb!vm
::current-thread-offset-sap sb
!vm
::thread-this-slot
))
75 (declaim (inline current-thread-sap-id
))
76 (defun current-thread-sap-id ()
78 (sb!vm
::current-thread-offset-sap sb
!vm
::thread-os-thread-slot
)))
80 (defun init-initial-thread ()
81 (/show0
"Entering INIT-INITIAL-THREAD")
82 (let ((initial-thread (%make-thread
:name
"initial thread"
84 :os-thread
(current-thread-sap-id))))
85 (setq *current-thread
* initial-thread
)
86 ;; Either *all-threads* is empty or it contains exactly one thread
87 ;; in case we are in reinit since saving core with multiple
88 ;; threads doesn't work.
89 (setq *all-threads
* (list initial-thread
))))
95 ;; FIXME it would be good to define what a thread id is or isn't
96 ;; (our current assumption is that it's a fixnum). It so happens
97 ;; that on Linux it's a pid, but it might not be on posix thread
99 (define-alien-routine ("create_thread" %create-thread
)
100 unsigned-long
(lisp-fun-address unsigned-long
))
102 (define-alien-routine "signal_interrupt_thread"
103 integer
(os-thread unsigned-long
))
105 (define-alien-routine "block_deferrable_signals"
110 (declaim (inline %lutex-init %lutex-wait %lutex-wake
111 %lutex-lock %lutex-unlock
))
113 (define-alien-routine ("lutex_init" %lutex-init
)
114 int
(lutex unsigned-long
))
116 (define-alien-routine ("lutex_wait" %lutex-wait
)
117 int
(queue-lutex unsigned-long
) (mutex-lutex unsigned-long
))
119 (define-alien-routine ("lutex_wake" %lutex-wake
)
120 int
(lutex unsigned-long
) (n int
))
122 (define-alien-routine ("lutex_lock" %lutex-lock
)
123 int
(lutex unsigned-long
))
125 (define-alien-routine ("lutex_trylock" %lutex-trylock
)
126 int
(lutex unsigned-long
))
128 (define-alien-routine ("lutex_unlock" %lutex-unlock
)
129 int
(lutex unsigned-long
))
131 (define-alien-routine ("lutex_destroy" %lutex-destroy
)
132 int
(lutex unsigned-long
))
134 ;; FIXME: Defining a whole bunch of alien-type machinery just for
135 ;; passing primitive lutex objects directly to foreign functions
136 ;; doesn't seem like fun right now. So instead we just manually
137 ;; pin the lutex, get its address, and let the callee untag it.
138 (defmacro with-lutex-address
((name lutex
) &body body
)
139 `(let ((,name
,lutex
))
140 (with-pinned-objects (,name
)
141 (let ((,name
(get-lisp-obj-address ,name
)))
145 (/show0
"Entering MAKE-LUTEX")
146 ;; Suppress GC until the lutex has been properly registered with
149 (let ((lutex (sb!vm
::%make-lutex
)))
152 (with-lutex-address (lutex lutex
)
158 (declaim (inline futex-wait %futex-wait futex-wake
))
160 (define-alien-routine ("futex_wait" %futex-wait
)
161 int
(word unsigned-long
) (old-value unsigned-long
)
162 (to-sec long
) (to-usec unsigned-long
))
164 (defun futex-wait (word old to-sec to-usec
)
166 (%futex-wait word old to-sec to-usec
)))
168 (define-alien-routine "futex_wake"
169 int
(word unsigned-long
) (n unsigned-long
))))
171 ;;; used by debug-int.lisp to access interrupt contexts
172 #!-
(or sb-fluid sb-thread
) (declaim (inline sb
!vm
::current-thread-offset-sap
))
174 (defun sb!vm
::current-thread-offset-sap
(n)
175 (declare (type (unsigned-byte 27) n
))
176 (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t
)))
177 (* n sb
!vm
:n-word-bytes
)))
180 (defun sb!vm
::current-thread-offset-sap
(n)
181 (declare (type (unsigned-byte 27) n
))
182 (sb!vm
::current-thread-offset-sap n
))
184 (declaim (inline get-spinlock release-spinlock
))
186 ;; Should always be called with interrupts disabled.
187 (defun get-spinlock (spinlock)
188 (declare (optimize (speed 3) (safety 0)))
189 (let* ((new *current-thread
*)
190 (old (sb!ext
:compare-and-swap
(spinlock-value spinlock
) nil new
)))
193 (error "Recursive lock attempt on ~S." spinlock
))
196 (unless (sb!ext
:compare-and-swap
(spinlock-value spinlock
) nil new
)
197 (return-from get-spinlock t
))))
198 (if (and (not *interrupts-enabled
*) *allow-with-interrupts
*)
199 ;; If interrupts are enabled, but we are allowed to enabled them,
200 ;; check for pending interrupts every once in a while.
202 (loop repeat
128 do
(cas)) ; 128 is arbitrary here
203 (sb!unix
::%check-interrupts
))
207 (defun release-spinlock (spinlock)
208 (declare (optimize (speed 3) (safety 0)))
209 (setf (spinlock-value spinlock
) nil
)
215 (setf (fdocumentation 'make-mutex
'function
)
217 (fdocumentation 'mutex-name
'function
)
218 "The name of the mutex. Setfable.")
220 #!+(and sb-thread
(not sb-lutex
))
222 (define-structure-slot-addressor mutex-state-address
225 ;; Important: current code assumes these are fixnums or other
226 ;; lisp objects that don't need pinning.
227 (defconstant +lock-free
+ 0)
228 (defconstant +lock-taken
+ 1)
229 (defconstant +lock-contested
+ 2))
231 (defun get-mutex (mutex &optional
(new-owner *current-thread
*) (waitp t
))
233 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
234 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
235 non-NIL and the mutex is in use, sleep until it is available.
237 Note: using GET-MUTEX to assign a MUTEX to another thread then the
238 current one is not recommended, and liable to be deprecated.
240 GET-MUTEX is not interrupt safe. The correct way to call it is:
244 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
247 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
248 call while the mutex is in an inconsistent state while
249 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
251 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
253 (declare (type mutex mutex
) (optimize (speed 3))
254 #!-sb-thread
(ignore waitp
))
256 (setq new-owner
*current-thread
*))
257 (when (eql new-owner
(mutex-%owner mutex
))
258 (error "Recursive lock attempt ~S." mutex
))
261 ;; FIXME: Lutexes do not currently support deadlines, as at least
262 ;; on Darwin pthread_foo_timedbar functions are not supported:
263 ;; this means that we probably need to use the Carbon multiprocessing
264 ;; functions on Darwin.
266 ;; FIXME: This is definitely not interrupt safe: what happens if
267 ;; we get hit (1) during the lutex calls (ok, they may be safe,
268 ;; but has that been checked?) (2) after the lutex call, but
269 ;; before setting the mutex owner.
271 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex
))
273 (with-interrupts (%lutex-lock lutex
))
274 (%lutex-trylock lutex
))))
275 (setf (mutex-%owner mutex
) new-owner
)
278 (let ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
281 (unless (or (eql +lock-free
+ old
) (not waitp
))
284 (when (or (eql +lock-contested
+ old
)
285 (not (eql +lock-free
+
286 (sb!ext
:compare-and-swap
(mutex-state mutex
)
289 ;; Wait on the contested lock.
290 (multiple-value-bind (to-sec to-usec
) (decode-timeout nil
)
291 (when (= 1 (with-pinned-objects (mutex)
292 (futex-wait (mutex-state-address mutex
)
293 (get-lisp-obj-address +lock-contested
+)
297 (setf old
(sb!ext
:compare-and-swap
(mutex-state mutex
)
301 (unless (eql +lock-free
+ old
)
303 (cond ((eql +lock-free
+ old
)
304 (let ((prev (sb!ext
:compare-and-swap
(mutex-%owner mutex
)
307 (bug "Old owner in free mutex: ~S" prev
))
310 (bug "Failed to acquire lock with WAITP."))))))
312 (defun release-mutex (mutex)
314 "Release MUTEX by setting it to NIL. Wake up threads waiting for
317 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
320 Signals a WARNING is current thread is not the current owner of the
322 (declare (type mutex mutex
))
323 ;; Order matters: set owner to NIL before releasing state.
324 (let* ((self *current-thread
*)
325 (old-owner (sb!ext
:compare-and-swap
(mutex-%owner mutex
) self nil
)))
326 (unless (eql self old-owner
)
327 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner
)
328 (setf (mutex-%owner mutex
) nil
)))
332 (with-lutex-address (lutex (mutex-lutex mutex
))
333 (%lutex-unlock lutex
))
335 (let ((old (sb!ext
:compare-and-swap
(mutex-state mutex
)
336 +lock-taken
+ +lock-free
+)))
337 (when (eql old
+lock-contested
+)
338 (sb!ext
:compare-and-swap
(mutex-state mutex
)
339 +lock-contested
+ +lock-free
+)
340 (with-pinned-objects (mutex)
341 (futex-wake (mutex-state-address mutex
) 1))))
344 ;;;; waitqueues/condition variables
346 (defstruct (waitqueue (:constructor %make-waitqueue
))
349 (name nil
:type
(or null simple-string
))
350 #!+(and sb-lutex sb-thread
)
355 (defun make-waitqueue (&key name
)
357 "Create a waitqueue."
358 (%make-waitqueue
:name name
))
361 (setf (fdocumentation 'waitqueue-name
'function
)
362 "The name of the waitqueue. Setfable.")
364 #!+(and sb-thread
(not sb-lutex
))
365 (define-structure-slot-addressor waitqueue-data-address
369 (defun condition-wait (queue mutex
)
371 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
372 thread may subsequently notify us using CONDITION-NOTIFY, at which
373 time we reacquire MUTEX and return to the caller."
374 #!-sb-thread
(declare (ignore queue
))
376 #!-sb-thread
(error "Not supported in unithread builds.")
378 (let ((owner (mutex-%owner mutex
)))
379 (/show0
"CONDITION-WAITing")
382 ;; FIXME: This doesn't look interrupt safe!
383 (setf (mutex-%owner mutex
) nil
)
384 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue
))
385 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex
))
386 (%lutex-wait queue-lutex-address mutex-lutex-address
)))
387 (setf (mutex-%owner mutex
) owner
))
390 (let ((me *current-thread
*))
391 ;; FIXME: should we do something to ensure that the result
392 ;; of this setf is visible to all CPUs?
393 (setf (waitqueue-data queue
) me
)
394 (release-mutex mutex
)
395 ;; Now we go to sleep using futex-wait. If anyone else
396 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
397 ;; this comment, it will change queue->data, and so
398 ;; futex-wait returns immediately instead of sleeping.
399 ;; Ergo, no lost wakeup. We may get spurious wakeups,
401 (multiple-value-bind (to-sec to-usec
) (decode-timeout nil
)
402 (when (= 1 (with-pinned-objects (queue me
)
403 (futex-wait (waitqueue-data-address queue
)
404 (get-lisp-obj-address me
)
405 (or to-sec -
1) ;; our way if saying "no timeout"
408 ;; If we are interrupted while waiting, we should do these things
409 ;; before returning. Ideally, in the case of an unhandled signal,
410 ;; we should do them before entering the debugger, but this is
411 ;; better than nothing.
412 (get-mutex mutex owner
))))
414 (defun condition-notify (queue &optional
(n 1))
416 "Notify N threads waiting on QUEUE."
417 #!-sb-thread
(declare (ignore queue n
))
418 #!-sb-thread
(error "Not supported in unithread builds.")
420 (declare (type (and fixnum
(integer 1)) n
))
421 (/show0
"Entering CONDITION-NOTIFY")
425 (with-lutex-address (lutex (waitqueue-lutex queue
))
426 (%lutex-wake lutex n
))
427 ;; no problem if >1 thread notifies during the comment in
428 ;; condition-wait: as long as the value in queue-data isn't the
429 ;; waiting thread's id, it matters not what it is
430 ;; XXX we should do something to ensure that the result of this setf
431 ;; is visible to all CPUs
433 (let ((me *current-thread
*))
435 (setf (waitqueue-data queue
) me
)
436 (with-pinned-objects (queue)
437 (futex-wake (waitqueue-data-address queue
) n
))))))
439 (defun condition-broadcast (queue)
441 "Notify all threads waiting on QUEUE."
442 (condition-notify queue
443 ;; On a 64-bit platform truncating M-P-F to an int results
444 ;; in -1, which wakes up only one thread.
446 most-positive-fixnum
)))
450 (defstruct (semaphore (:constructor %make-semaphore
(name %count
)))
452 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
453 should be considered an implementation detail, and may change in the
455 (name nil
:type
(or null simple-string
))
456 (%count
0 :type
(integer 0))
458 (queue (make-waitqueue)))
460 (setf (fdocumentation 'semaphore-name
'function
)
461 "The name of the semaphore INSTANCE. Setfable.")
463 (declaim (inline semaphore-count
))
464 (defun semaphore-count (instance)
465 "Returns the current count of the semaphore INSTANCE."
466 (semaphore-%count instance
))
468 (defun make-semaphore (&key name
(count 0))
470 "Create a semaphore with the supplied COUNT and NAME."
471 (%make-semaphore name count
))
473 (defun wait-on-semaphore (semaphore)
475 "Decrement the count of SEMAPHORE if the count would not be
476 negative. Else blocks until the semaphore can be decremented."
477 ;; a more direct implementation based directly on futexes should be
479 (with-mutex ((semaphore-mutex semaphore
))
480 (loop until
(> (semaphore-%count semaphore
) 0)
481 do
(condition-wait (semaphore-queue semaphore
) (semaphore-mutex semaphore
))
482 finally
(decf (semaphore-%count semaphore
)))))
484 (defun signal-semaphore (semaphore &optional
(n 1))
486 "Increment the count of SEMAPHORE by N. If there are threads waiting
487 on this semaphore, then N of them is woken up."
488 (declare (type (integer 1) n
))
489 (with-mutex ((semaphore-mutex semaphore
))
490 (when (= n
(incf (semaphore-%count semaphore
) n
))
491 (condition-notify (semaphore-queue semaphore
) n
))))
493 ;;;; job control, independent listeners
496 (lock (make-mutex :name
"session lock"))
498 (interactive-threads nil
)
499 (interactive-threads-queue (make-waitqueue)))
501 (defvar *session
* nil
)
503 ;;; the debugger itself tries to acquire the session lock, don't let
504 ;;; funny situations (like getting a sigint while holding the session
506 (defmacro with-session-lock
((session) &body body
)
507 `(call-with-system-mutex (lambda () ,@body
) (session-lock ,session
)))
509 (defun new-session ()
510 (make-session :threads
(list *current-thread
*)
511 :interactive-threads
(list *current-thread
*)))
513 (defun init-job-control ()
514 (/show0
"Entering INIT-JOB-CONTROL")
515 (setf *session
* (new-session))
516 (/show0
"Exiting INIT-JOB-CONTROL"))
518 (defun %delete-thread-from-session
(thread session
)
519 (with-session-lock (session)
520 (setf (session-threads session
)
521 (delete thread
(session-threads session
))
522 (session-interactive-threads session
)
523 (delete thread
(session-interactive-threads session
)))))
525 (defun call-with-new-session (fn)
526 (%delete-thread-from-session
*current-thread
* *session
*)
527 (let ((*session
* (new-session)))
530 (defmacro with-new-session
(args &body forms
)
531 (declare (ignore args
)) ;for extensibility
532 (sb!int
:with-unique-names
(fb-name)
533 `(labels ((,fb-name
() ,@forms
))
534 (call-with-new-session (function ,fb-name
)))))
536 ;;; Remove thread from its session, if it has one.
538 (defun handle-thread-exit (thread)
539 (/show0
"HANDLING THREAD EXIT")
540 ;; We're going down, can't handle interrupts sanely anymore.
541 ;; GC remains enabled.
542 (block-deferrable-signals)
544 (with-all-threads-lock
545 (setf (thread-%alive-p thread
) nil
)
546 (setf (thread-os-thread thread
) nil
)
547 (setq *all-threads
* (delete thread
*all-threads
*))
549 (%delete-thread-from-session thread
*session
*)))
552 (/show0
"FREEING MUTEX LUTEX")
553 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread
)))
554 (%lutex-destroy lutex
))))
556 (defun terminate-session ()
558 "Kill all threads in session except for this one. Does nothing if current
559 thread is not the foreground thread."
560 ;; FIXME: threads created in other threads may escape termination
562 (with-session-lock (*session
*)
563 (and (eq *current-thread
*
564 (car (session-interactive-threads *session
*)))
565 (session-threads *session
*)))))
566 ;; do the kill after dropping the mutex; unwind forms in dying
567 ;; threads may want to do session things
568 (dolist (thread to-kill
)
569 (unless (eq thread
*current-thread
*)
570 ;; terminate the thread but don't be surprised if it has
571 ;; exited in the meantime
572 (handler-case (terminate-thread thread
)
573 (interrupt-thread-error ()))))))
575 ;;; called from top of invoke-debugger
576 (defun debugger-wait-until-foreground-thread (stream)
577 "Returns T if thread had been running in background, NIL if it was
579 (declare (ignore stream
))
583 (with-session-lock (*session
*)
584 (not (member *current-thread
*
585 (session-interactive-threads *session
*))))
588 (defun get-foreground ()
591 (let ((was-foreground t
))
593 (/show0
"Looping in GET-FOREGROUND")
594 (with-session-lock (*session
*)
595 (let ((int-t (session-interactive-threads *session
*)))
596 (when (eq (car int-t
) *current-thread
*)
597 (unless was-foreground
598 (format *query-io
* "Resuming thread ~A~%" *current-thread
*))
599 (return-from get-foreground t
))
600 (setf was-foreground nil
)
601 (unless (member *current-thread
* int-t
)
602 (setf (cdr (last int-t
))
603 (list *current-thread
*)))
605 (session-interactive-threads-queue *session
*)
606 (session-lock *session
*)))))))
608 (defun release-foreground (&optional next
)
610 "Background this thread. If NEXT is supplied, arrange for it to
611 have the foreground next."
612 #!-sb-thread
(declare (ignore next
))
615 (with-session-lock (*session
*)
616 (when (rest (session-interactive-threads *session
*))
617 (setf (session-interactive-threads *session
*)
618 (delete *current-thread
* (session-interactive-threads *session
*))))
620 (setf (session-interactive-threads *session
*)
622 (delete next
(session-interactive-threads *session
*)))))
623 (condition-broadcast (session-interactive-threads-queue *session
*))))
625 (defun foreground-thread ()
626 (car (session-interactive-threads *session
*)))
628 (defun make-listener-thread (tty-name)
629 (assert (probe-file tty-name
))
630 (let* ((in (sb!unix
:unix-open
(namestring tty-name
) sb
!unix
:o_rdwr
#o666
))
631 (out (sb!unix
:unix-dup in
))
632 (err (sb!unix
:unix-dup in
)))
633 (labels ((thread-repl ()
634 (sb!unix
::unix-setsid
)
635 (let* ((sb!impl
::*stdin
*
636 (make-fd-stream in
:input t
:buffering
:line
639 (make-fd-stream out
:output t
:buffering
:line
642 (make-fd-stream err
:output t
:buffering
:line
645 (make-fd-stream err
:input t
:output t
648 (sb!impl
::*descriptor-handlers
* nil
))
651 (sb!impl
::toplevel-repl nil
)
652 (sb!int
:flush-standard-output-streams
))))))
653 (make-thread #'thread-repl
))))
657 (defun make-thread (function &key name
)
659 "Create a new thread of NAME that runs FUNCTION. When the function
660 returns the thread exits. The return values of FUNCTION are kept
661 around and can be retrieved by JOIN-THREAD."
662 #!-sb-thread
(declare (ignore function name
))
663 #!-sb-thread
(error "Not supported in unithread builds.")
665 (let* ((thread (%make-thread
:name name
))
666 (setup-sem (make-semaphore :name
"Thread setup semaphore"))
667 (real-function (coerce function
'function
))
670 ;; In time we'll move some of the binding presently done in C
673 ;; KLUDGE: Here we have a magic list of variables that are
674 ;; not thread-safe for one reason or another. As people
675 ;; report problems with the thread safety of certain
676 ;; variables, (e.g. "*print-case* in multiple threads
677 ;; broken", sbcl-devel 2006-07-14), we add a few more
678 ;; bindings here. The Right Thing is probably some variant
679 ;; of Allegro's *cl-default-special-bindings*, as that is at
680 ;; least accessible to users to secure their own libraries.
682 (let* ((*current-thread
* thread
)
683 (*restart-clusters
* nil
)
684 (*handler-clusters
* nil
)
685 (*condition-restarts
* nil
)
686 (sb!impl
::*deadline
* nil
)
687 (sb!impl
::*step-out
* nil
)
688 ;; internal printer variables
689 (sb!impl
::*previous-case
* nil
)
690 (sb!impl
::*previous-readtable-case
* nil
)
692 (sb!impl
::*merge-sort-temp-vector
* empty
)
693 (sb!impl
::*zap-array-data-temp
* empty
)
694 (sb!impl
::*internal-symbol-output-fun
* nil
)
695 (sb!impl
::*descriptor-handlers
* nil
)) ; serve-event
696 (setf (thread-os-thread thread
) (current-thread-sap-id))
697 (with-mutex ((thread-result-lock thread
))
698 (with-all-threads-lock
699 (push thread
*all-threads
*))
700 (with-session-lock (*session
*)
701 (push thread
(session-threads *session
*)))
702 (setf (thread-%alive-p thread
) t
)
703 (signal-semaphore setup-sem
)
704 ;; can't use handling-end-of-the-world, because that flushes
705 ;; output streams, and we don't necessarily have any (or we
706 ;; could be sharing them)
707 (catch 'sb
!impl
::toplevel-catcher
708 (catch 'sb
!impl
::%end-of-the-world
712 "~~@<Terminate this thread (~A)~~@:>"
716 ;; now that most things have a chance to
717 ;; work properly without messing up other
718 ;; threads, it's time to enable signals
719 (sb!unix
::reset-signal-mask
)
720 (setf (thread-result thread
)
723 (funcall real-function
)))))
724 (handle-thread-exit thread
)))))))
726 ;; Keep INITIAL-FUNCTION pinned until the child thread is
727 ;; initialized properly.
728 (with-pinned-objects (initial-function)
731 (get-lisp-obj-address initial-function
))))
732 (when (zerop os-thread
)
733 (error "Can't create a new thread"))
734 (wait-on-semaphore setup-sem
)
737 (define-condition join-thread-error
(error)
738 ((thread :reader join-thread-error-thread
:initarg
:thread
))
740 (:documentation
"Joining thread failed.")
741 (:report
(lambda (c s
)
742 (format s
"Joining thread failed: thread ~A ~
743 has not returned normally."
744 (join-thread-error-thread c
)))))
747 (setf (fdocumentation 'join-thread-error-thread
'function
)
748 "The thread that we failed to join.")
750 (defun join-thread (thread &key
(default nil defaultp
))
752 "Suspend current thread until THREAD exits. Returns the result
753 values of the thread function. If the thread does not exit normally,
754 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
755 (with-mutex ((thread-result-lock thread
))
756 (cond ((car (thread-result thread
))
757 (values-list (cdr (thread-result thread
))))
761 (error 'join-thread-error
:thread thread
)))))
763 (defun destroy-thread (thread)
765 "Deprecated. Same as TERMINATE-THREAD."
766 (terminate-thread thread
))
768 (define-condition interrupt-thread-error
(error)
769 ((thread :reader interrupt-thread-error-thread
:initarg
:thread
))
771 (:documentation
"Interrupting thread failed.")
772 (:report
(lambda (c s
)
773 (format s
"Interrupt thread failed: thread ~A has exited."
774 (interrupt-thread-error-thread c
)))))
777 (setf (fdocumentation 'interrupt-thread-error-thread
'function
)
778 "The thread that was not interrupted.")
780 (defmacro with-interruptions-lock
((thread) &body body
)
781 `(call-with-system-mutex (lambda () ,@body
) (thread-interruptions-lock ,thread
)))
783 ;; Called from the signal handler in C.
784 (defun run-interruption ()
787 (let ((interruption (with-interruptions-lock (*current-thread
*)
788 (pop (thread-interruptions *current-thread
*)))))
791 (funcall interruption
))
794 ;; The order of interrupt execution is peculiar. If thread A
795 ;; interrupts thread B with I1, I2 and B for some reason receives I1
796 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
797 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
798 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
799 ;; just one scenario, and the order of thread interrupt execution is
801 (defun interrupt-thread (thread function
)
803 "Interrupt the live THREAD and make it run FUNCTION. A moderate
804 degree of care is expected for use of INTERRUPT-THREAD, due to its
805 nature: if you interrupt a thread that was holding important locks
806 then do something that turns out to need those locks, you probably
807 won't like the effect."
808 #!-sb-thread
(declare (ignore thread
))
810 (with-interrupt-bindings
811 (with-interrupts (funcall function
)))
813 (if (eq thread
*current-thread
*)
814 (with-interrupt-bindings
815 (with-interrupts (funcall function
)))
816 (let ((os-thread (thread-os-thread thread
)))
817 (cond ((not os-thread
)
818 (error 'interrupt-thread-error
:thread thread
))
820 (with-interruptions-lock (thread)
821 (push function
(thread-interruptions thread
)))
822 (when (minusp (signal-interrupt-thread os-thread
))
823 (error 'interrupt-thread-error
:thread thread
)))))))
825 (defun terminate-thread (thread)
827 "Terminate the thread identified by THREAD, by causing it to run
828 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
829 (interrupt-thread thread
'sb
!ext
:quit
))
831 ;;; internal use only. If you think you need to use this, either you
832 ;;; are an SBCL developer, are doing something that you should discuss
833 ;;; with an SBCL developer first, or are doing something that you
834 ;;; should probably discuss with a professional psychiatrist first
836 (defun thread-sap-for-id (id)
837 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t
)))))
839 (when (sap= thread-sap
(int-sap 0)) (return nil
))
840 (let ((os-thread (sap-ref-word thread-sap
841 (* sb
!vm
:n-word-bytes
842 sb
!vm
::thread-os-thread-slot
))))
843 (when (= os-thread id
) (return thread-sap
))
845 (sap-ref-sap thread-sap
(* sb
!vm
:n-word-bytes
846 sb
!vm
::thread-next-slot
)))))))
848 (define-alien-routine "thread_yield" int
)
851 (setf (fdocumentation 'thread-yield
'function
)
852 "Yield the processor to other threads.")
855 (defun symbol-value-in-thread (symbol thread-sap
)
856 (let* ((index (sb!vm
::symbol-tls-index symbol
))
857 (tl-val (sap-ref-word thread-sap
858 (* sb
!vm
:n-word-bytes index
))))
859 (if (eql tl-val sb
!vm
::no-tls-value-marker-widetag
)
860 (sb!vm
::symbol-global-value symbol
)
861 (make-lisp-obj tl-val
))))
863 (defun sb!vm
::locked-symbol-global-value-add
(symbol-name delta
)
864 (sb!vm
::locked-symbol-global-value-add symbol-name delta
))
868 (defun thread-stepping ()
870 (sap-ref-word (current-thread-sap)
871 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
))))
873 (defun (setf thread-stepping
) (value)
874 (setf (sap-ref-word (current-thread-sap)
875 (* sb
!vm
::thread-stepping-slot sb
!vm
:n-word-bytes
))
876 (get-lisp-obj-address value
)))