1.0.19.33: Improved interrupt handling on darwin/x86[-64]
[sbcl/pkhuong.git] / src / code / target-thread.lisp
blob27e686c0f7f02b6a9424f4e4f2d5cd57ae48fa59
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 ((owner (mutex-%owner mutex)))
391 (/show0 "CONDITION-WAITing")
392 #!+sb-lutex
393 (progn
394 ;; FIXME: This doesn't look interrupt safe!
395 (setf (mutex-%owner mutex) nil)
396 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
397 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
398 (%lutex-wait queue-lutex-address mutex-lutex-address)))
399 (setf (mutex-%owner mutex) owner))
400 #!-sb-lutex
401 (unwind-protect
402 (let ((me *current-thread*))
403 ;; FIXME: should we do something to ensure that the result
404 ;; of this setf is visible to all CPUs?
405 (setf (waitqueue-data queue) me)
406 (release-mutex mutex)
407 ;; Now we go to sleep using futex-wait. If anyone else
408 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
409 ;; this comment, it will change queue->data, and so
410 ;; futex-wait returns immediately instead of sleeping.
411 ;; Ergo, no lost wakeup. We may get spurious wakeups,
412 ;; but that's ok.
413 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
414 (when (= 1 (with-pinned-objects (queue me)
415 (futex-wait (waitqueue-data-address queue)
416 (get-lisp-obj-address me)
417 (or to-sec -1) ;; our way if saying "no timeout"
418 (or to-usec 0))))
419 (signal-deadline))))
420 ;; If we are interrupted while waiting, we should do these things
421 ;; before returning. Ideally, in the case of an unhandled signal,
422 ;; we should do them before entering the debugger, but this is
423 ;; better than nothing.
424 (get-mutex mutex owner))))
426 (defun condition-notify (queue &optional (n 1))
427 #!+sb-doc
428 "Notify N threads waiting on QUEUE."
429 #!-sb-thread (declare (ignore queue n))
430 #!-sb-thread (error "Not supported in unithread builds.")
431 #!+sb-thread
432 (declare (type (and fixnum (integer 1)) n))
433 (/show0 "Entering CONDITION-NOTIFY")
434 #!+sb-thread
435 (progn
436 #!+sb-lutex
437 (with-lutex-address (lutex (waitqueue-lutex queue))
438 (%lutex-wake lutex n))
439 ;; no problem if >1 thread notifies during the comment in
440 ;; condition-wait: as long as the value in queue-data isn't the
441 ;; waiting thread's id, it matters not what it is
442 ;; XXX we should do something to ensure that the result of this setf
443 ;; is visible to all CPUs
444 #!-sb-lutex
445 (let ((me *current-thread*))
446 (progn
447 (setf (waitqueue-data queue) me)
448 (with-pinned-objects (queue)
449 (futex-wake (waitqueue-data-address queue) n))))))
451 (defun condition-broadcast (queue)
452 #!+sb-doc
453 "Notify all threads waiting on QUEUE."
454 (condition-notify queue
455 ;; On a 64-bit platform truncating M-P-F to an int results
456 ;; in -1, which wakes up only one thread.
457 (ldb (byte 29 0)
458 most-positive-fixnum)))
460 ;;;; semaphores
462 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
463 #!+sb-doc
464 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
465 should be considered an implementation detail, and may change in the
466 future."
467 (name nil :type (or null simple-string))
468 (%count 0 :type (integer 0))
469 (mutex (make-mutex))
470 (queue (make-waitqueue)))
472 (setf (fdocumentation 'semaphore-name 'function)
473 "The name of the semaphore INSTANCE. Setfable.")
475 (declaim (inline semaphore-count))
476 (defun semaphore-count (instance)
477 "Returns the current count of the semaphore INSTANCE."
478 (semaphore-%count instance))
480 (defun make-semaphore (&key name (count 0))
481 #!+sb-doc
482 "Create a semaphore with the supplied COUNT and NAME."
483 (%make-semaphore name count))
485 (defun wait-on-semaphore (semaphore)
486 #!+sb-doc
487 "Decrement the count of SEMAPHORE if the count would not be
488 negative. Else blocks until the semaphore can be decremented."
489 ;; a more direct implementation based directly on futexes should be
490 ;; possible
491 (with-mutex ((semaphore-mutex semaphore))
492 (loop until (> (semaphore-%count semaphore) 0)
493 do (condition-wait (semaphore-queue semaphore) (semaphore-mutex semaphore))
494 finally (decf (semaphore-%count semaphore)))))
496 (defun signal-semaphore (semaphore &optional (n 1))
497 #!+sb-doc
498 "Increment the count of SEMAPHORE by N. If there are threads waiting
499 on this semaphore, then N of them is woken up."
500 (declare (type (integer 1) n))
501 (with-mutex ((semaphore-mutex semaphore))
502 (when (= n (incf (semaphore-%count semaphore) n))
503 (condition-notify (semaphore-queue semaphore) n))))
505 ;;;; job control, independent listeners
507 (defstruct session
508 (lock (make-mutex :name "session lock"))
509 (threads nil)
510 (interactive-threads nil)
511 (interactive-threads-queue (make-waitqueue)))
513 (defvar *session* nil)
515 ;;; The debugger itself tries to acquire the session lock, don't let
516 ;;; funny situations (like getting a sigint while holding the session
517 ;;; lock) occur. At the same time we need to allow interrupts while
518 ;;; *waiting* for the session lock for things like GET-FOREGROUND
519 ;;; to be interruptible.
521 ;;; Take care: we sometimes need to obtain the session lock while holding
522 ;;; on to *ALL-THREADS-LOCK*, so we must _never_ obtain it _after_ getting
523 ;;; a session lock! (Deadlock risk.)
525 ;;; FIXME: It would be good to have ordered locks to ensure invariants like
526 ;;; the above.
527 (defmacro with-session-lock ((session) &body body)
528 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
529 ,@body))
531 (defun new-session ()
532 (make-session :threads (list *current-thread*)
533 :interactive-threads (list *current-thread*)))
535 (defun init-job-control ()
536 (/show0 "Entering INIT-JOB-CONTROL")
537 (setf *session* (new-session))
538 (/show0 "Exiting INIT-JOB-CONTROL"))
540 (defun %delete-thread-from-session (thread session)
541 (with-session-lock (session)
542 (setf (session-threads session)
543 (delete thread (session-threads session))
544 (session-interactive-threads session)
545 (delete thread (session-interactive-threads session)))))
547 (defun call-with-new-session (fn)
548 (%delete-thread-from-session *current-thread* *session*)
549 (let ((*session* (new-session)))
550 (funcall fn)))
552 (defmacro with-new-session (args &body forms)
553 (declare (ignore args)) ;for extensibility
554 (sb!int:with-unique-names (fb-name)
555 `(labels ((,fb-name () ,@forms))
556 (call-with-new-session (function ,fb-name)))))
558 ;;; Remove thread from its session, if it has one.
559 #!+sb-thread
560 (defun handle-thread-exit (thread)
561 (/show0 "HANDLING THREAD EXIT")
562 ;; We're going down, can't handle interrupts sanely anymore.
563 ;; GC remains enabled.
564 (block-deferrable-signals)
565 ;; Lisp-side cleanup
566 (with-all-threads-lock
567 (setf (thread-%alive-p thread) nil)
568 (setf (thread-os-thread thread) nil)
569 (setq *all-threads* (delete thread *all-threads*))
570 (when *session*
571 (%delete-thread-from-session thread *session*)))
572 #!+sb-lutex
573 (without-gcing
574 (/show0 "FREEING MUTEX LUTEX")
575 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
576 (%lutex-destroy lutex))))
578 (defun terminate-session ()
579 #!+sb-doc
580 "Kill all threads in session except for this one. Does nothing if current
581 thread is not the foreground thread."
582 ;; FIXME: threads created in other threads may escape termination
583 (let ((to-kill
584 (with-session-lock (*session*)
585 (and (eq *current-thread*
586 (car (session-interactive-threads *session*)))
587 (session-threads *session*)))))
588 ;; do the kill after dropping the mutex; unwind forms in dying
589 ;; threads may want to do session things
590 (dolist (thread to-kill)
591 (unless (eq thread *current-thread*)
592 ;; terminate the thread but don't be surprised if it has
593 ;; exited in the meantime
594 (handler-case (terminate-thread thread)
595 (interrupt-thread-error ()))))))
597 ;;; called from top of invoke-debugger
598 (defun debugger-wait-until-foreground-thread (stream)
599 "Returns T if thread had been running in background, NIL if it was
600 interactive."
601 (declare (ignore stream))
602 #!-sb-thread nil
603 #!+sb-thread
604 (prog1
605 (with-session-lock (*session*)
606 (not (member *current-thread*
607 (session-interactive-threads *session*))))
608 (get-foreground)))
610 (defun get-foreground ()
611 #!-sb-thread t
612 #!+sb-thread
613 (let ((was-foreground t))
614 (loop
615 (/show0 "Looping in GET-FOREGROUND")
616 (with-session-lock (*session*)
617 (let ((int-t (session-interactive-threads *session*)))
618 (when (eq (car int-t) *current-thread*)
619 (unless was-foreground
620 (format *query-io* "Resuming thread ~A~%" *current-thread*))
621 (return-from get-foreground t))
622 (setf was-foreground nil)
623 (unless (member *current-thread* int-t)
624 (setf (cdr (last int-t))
625 (list *current-thread*)))
626 (condition-wait
627 (session-interactive-threads-queue *session*)
628 (session-lock *session*)))))))
630 (defun release-foreground (&optional next)
631 #!+sb-doc
632 "Background this thread. If NEXT is supplied, arrange for it to
633 have the foreground next."
634 #!-sb-thread (declare (ignore next))
635 #!-sb-thread nil
636 #!+sb-thread
637 (with-session-lock (*session*)
638 (when (rest (session-interactive-threads *session*))
639 (setf (session-interactive-threads *session*)
640 (delete *current-thread* (session-interactive-threads *session*))))
641 (when next
642 (setf (session-interactive-threads *session*)
643 (list* next
644 (delete next (session-interactive-threads *session*)))))
645 (condition-broadcast (session-interactive-threads-queue *session*))))
647 (defun foreground-thread ()
648 (car (session-interactive-threads *session*)))
650 (defun make-listener-thread (tty-name)
651 (assert (probe-file tty-name))
652 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
653 (out (sb!unix:unix-dup in))
654 (err (sb!unix:unix-dup in)))
655 (labels ((thread-repl ()
656 (sb!unix::unix-setsid)
657 (let* ((sb!impl::*stdin*
658 (make-fd-stream in :input t :buffering :line
659 :dual-channel-p t))
660 (sb!impl::*stdout*
661 (make-fd-stream out :output t :buffering :line
662 :dual-channel-p t))
663 (sb!impl::*stderr*
664 (make-fd-stream err :output t :buffering :line
665 :dual-channel-p t))
666 (sb!impl::*tty*
667 (make-fd-stream err :input t :output t
668 :buffering :line
669 :dual-channel-p t))
670 (sb!impl::*descriptor-handlers* nil))
671 (with-new-session ()
672 (unwind-protect
673 (sb!impl::toplevel-repl nil)
674 (sb!int:flush-standard-output-streams))))))
675 (make-thread #'thread-repl))))
677 ;;;; the beef
679 (defun make-thread (function &key name)
680 #!+sb-doc
681 "Create a new thread of NAME that runs FUNCTION. When the function
682 returns the thread exits. The return values of FUNCTION are kept
683 around and can be retrieved by JOIN-THREAD."
684 #!-sb-thread (declare (ignore function name))
685 #!-sb-thread (error "Not supported in unithread builds.")
686 #!+sb-thread
687 (let* ((thread (%make-thread :name name))
688 (setup-sem (make-semaphore :name "Thread setup semaphore"))
689 (real-function (coerce function 'function))
690 (initial-function
691 (lambda ()
692 ;; In time we'll move some of the binding presently done in C
693 ;; here too.
695 ;; KLUDGE: Here we have a magic list of variables that are
696 ;; not thread-safe for one reason or another. As people
697 ;; report problems with the thread safety of certain
698 ;; variables, (e.g. "*print-case* in multiple threads
699 ;; broken", sbcl-devel 2006-07-14), we add a few more
700 ;; bindings here. The Right Thing is probably some variant
701 ;; of Allegro's *cl-default-special-bindings*, as that is at
702 ;; least accessible to users to secure their own libraries.
703 ;; --njf, 2006-07-15
704 (let* ((*current-thread* thread)
705 (*restart-clusters* nil)
706 (*handler-clusters* (sb!kernel::initial-handler-clusters))
707 (*condition-restarts* nil)
708 (sb!impl::*deadline* nil)
709 (sb!impl::*step-out* nil)
710 ;; internal printer variables
711 (sb!impl::*previous-case* nil)
712 (sb!impl::*previous-readtable-case* nil)
713 (empty (vector))
714 (sb!impl::*merge-sort-temp-vector* empty)
715 (sb!impl::*zap-array-data-temp* empty)
716 (sb!impl::*internal-symbol-output-fun* nil)
717 (sb!impl::*descriptor-handlers* nil)) ; serve-event
718 ;; Binding from C
719 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
720 (setf (thread-os-thread thread) (current-thread-os-thread))
721 (with-mutex ((thread-result-lock thread))
722 (with-all-threads-lock
723 (push thread *all-threads*))
724 (with-session-lock (*session*)
725 (push thread (session-threads *session*)))
726 (setf (thread-%alive-p thread) t)
727 (signal-semaphore setup-sem)
728 ;; can't use handling-end-of-the-world, because that flushes
729 ;; output streams, and we don't necessarily have any (or we
730 ;; could be sharing them)
731 (catch 'sb!impl::toplevel-catcher
732 (catch 'sb!impl::%end-of-the-world
733 (with-simple-restart
734 (terminate-thread
735 (format nil
736 "~~@<Terminate this thread (~A)~~@:>"
737 *current-thread*))
738 (unwind-protect
739 (progn
740 ;; now that most things have a chance to
741 ;; work properly without messing up other
742 ;; threads, it's time to enable signals
743 (sb!unix::reset-signal-mask)
744 (setf (thread-result thread)
745 (cons t
746 (multiple-value-list
747 (funcall real-function)))))
748 (handle-thread-exit thread)))))))
749 (values))))
750 ;; Keep INITIAL-FUNCTION pinned until the child thread is
751 ;; initialized properly.
752 (with-pinned-objects (initial-function)
753 (let ((os-thread
754 (%create-thread
755 (get-lisp-obj-address initial-function))))
756 (when (zerop os-thread)
757 (error "Can't create a new thread"))
758 (wait-on-semaphore setup-sem)
759 thread))))
761 (define-condition join-thread-error (error)
762 ((thread :reader join-thread-error-thread :initarg :thread))
763 #!+sb-doc
764 (:documentation "Joining thread failed.")
765 (:report (lambda (c s)
766 (format s "Joining thread failed: thread ~A ~
767 has not returned normally."
768 (join-thread-error-thread c)))))
770 #!+sb-doc
771 (setf (fdocumentation 'join-thread-error-thread 'function)
772 "The thread that we failed to join.")
774 (defun join-thread (thread &key (default nil defaultp))
775 #!+sb-doc
776 "Suspend current thread until THREAD exits. Returns the result
777 values of the thread function. If the thread does not exit normally,
778 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
779 (with-mutex ((thread-result-lock thread))
780 (cond ((car (thread-result thread))
781 (values-list (cdr (thread-result thread))))
782 (defaultp
783 default)
785 (error 'join-thread-error :thread thread)))))
787 (defun destroy-thread (thread)
788 #!+sb-doc
789 "Deprecated. Same as TERMINATE-THREAD."
790 (terminate-thread thread))
792 (define-condition interrupt-thread-error (error)
793 ((thread :reader interrupt-thread-error-thread :initarg :thread))
794 #!+sb-doc
795 (:documentation "Interrupting thread failed.")
796 (:report (lambda (c s)
797 (format s "Interrupt thread failed: thread ~A has exited."
798 (interrupt-thread-error-thread c)))))
800 #!+sb-doc
801 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
802 "The thread that was not interrupted.")
804 (defmacro with-interruptions-lock ((thread) &body body)
805 `(with-system-mutex ((thread-interruptions-lock ,thread))
806 ,@body))
808 ;; Called from the signal handler in C.
809 (defun run-interruption ()
810 (in-interruption ()
811 (loop
812 (let ((interruption (with-interruptions-lock (*current-thread*)
813 (pop (thread-interruptions *current-thread*)))))
814 (if interruption
815 (with-interrupts
816 (funcall interruption))
817 (return))))))
819 ;; The order of interrupt execution is peculiar. If thread A
820 ;; interrupts thread B with I1, I2 and B for some reason receives I1
821 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
822 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
823 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
824 ;; just one scenario, and the order of thread interrupt execution is
825 ;; undefined.
826 (defun interrupt-thread (thread function)
827 #!+sb-doc
828 "Interrupt the live THREAD and make it run FUNCTION. A moderate
829 degree of care is expected for use of INTERRUPT-THREAD, due to its
830 nature: if you interrupt a thread that was holding important locks
831 then do something that turns out to need those locks, you probably
832 won't like the effect."
833 #!-sb-thread (declare (ignore thread))
834 #!-sb-thread
835 (with-interrupt-bindings
836 (with-interrupts (funcall function)))
837 #!+sb-thread
838 (if (eq thread *current-thread*)
839 (with-interrupt-bindings
840 (with-interrupts (funcall function)))
841 (let ((os-thread (thread-os-thread thread)))
842 (cond ((not os-thread)
843 (error 'interrupt-thread-error :thread thread))
845 (with-interruptions-lock (thread)
846 (push function (thread-interruptions thread)))
847 (when (minusp (signal-interrupt-thread os-thread))
848 (error 'interrupt-thread-error :thread thread)))))))
850 (defun terminate-thread (thread)
851 #!+sb-doc
852 "Terminate the thread identified by THREAD, by causing it to run
853 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
854 (interrupt-thread thread 'sb!ext:quit))
856 (define-alien-routine "thread_yield" int)
858 #!+sb-doc
859 (setf (fdocumentation 'thread-yield 'function)
860 "Yield the processor to other threads.")
862 ;;; internal use only. If you think you need to use these, either you
863 ;;; are an SBCL developer, are doing something that you should discuss
864 ;;; with an SBCL developer first, or are doing something that you
865 ;;; should probably discuss with a professional psychiatrist first
866 #!+sb-thread
867 (progn
868 (defun %thread-sap (thread)
869 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
870 (target (thread-os-thread thread)))
871 (loop
872 (when (sap= thread-sap (int-sap 0)) (return nil))
873 (let ((os-thread (sap-ref-word thread-sap
874 (* sb!vm:n-word-bytes
875 sb!vm::thread-os-thread-slot))))
876 (when (= os-thread target) (return thread-sap))
877 (setf thread-sap
878 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
879 sb!vm::thread-next-slot)))))))
881 (defun %symbol-value-in-thread (symbol thread)
882 (tagbody
883 ;; Prevent the dead from dying completely while we look for the TLS area...
884 (with-all-threads-lock
885 (if (thread-alive-p thread)
886 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
887 (tl-val (sap-ref-word (%thread-sap thread) offset)))
888 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
889 (go :unbound)
890 (return-from %symbol-value-in-thread (values (make-lisp-obj tl-val) t))))
891 (return-from %symbol-value-in-thread (values nil nil))))
892 :unbound
893 (error "Cannot read thread-local symbol value: ~S unbound in ~S" symbol thread)))
895 (defun %set-symbol-value-in-thread (symbol thread value)
896 (tagbody
897 (with-pinned-objects (value)
898 ;; Prevent the dead from dying completely while we look for the TLS area...
899 (with-all-threads-lock
900 (if (thread-alive-p thread)
901 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
902 (sap (%thread-sap thread))
903 (tl-val (sap-ref-word sap offset)))
904 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
905 (go :unbound)
906 (setf (sap-ref-word sap offset) (get-lisp-obj-address value)))
907 (return-from %set-symbol-value-in-thread (values value t)))
908 (return-from %set-symbol-value-in-thread (values nil nil)))))
909 :unbound
910 (error "Cannot set thread-local symbol value: ~S unbound in ~S" symbol thread))))
912 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
913 (sb!vm::locked-symbol-global-value-add symbol-name delta))
915 ;;; Stepping
917 (defun thread-stepping ()
918 (make-lisp-obj
919 (sap-ref-word (current-thread-sap)
920 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
922 (defun (setf thread-stepping) (value)
923 (setf (sap-ref-word (current-thread-sap)
924 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
925 (get-lisp-obj-address value)))