1.0.18.17: Alter some STYLE-WARNING names introduced in 1.0.18.16.
[sbcl/pkhuong.git] / src / code / target-thread.lisp
blobc37afefa5dfa6b91ef1d53bca827cbd05d022f3d
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 (unless (sb!ext:compare-and-swap (spinlock-value spinlock) nil new)
208 (return-from get-spinlock t))))
209 (if (and (not *interrupts-enabled*) *allow-with-interrupts*)
210 ;; If interrupts are enabled, but we are allowed to enabled them,
211 ;; check for pending interrupts every once in a while.
212 (loop
213 (loop repeat 128 do (cas)) ; 128 is arbitrary here
214 (sb!unix::%check-interrupts))
215 (loop (cas)))))
218 (defun release-spinlock (spinlock)
219 (declare (optimize (speed 3) (safety 0)))
220 (setf (spinlock-value spinlock) nil)
221 nil)
223 ;;;; mutexes
225 #!+sb-doc
226 (setf (fdocumentation 'make-mutex 'function)
227 "Create a mutex."
228 (fdocumentation 'mutex-name 'function)
229 "The name of the mutex. Setfable.")
231 #!+(and sb-thread (not sb-lutex))
232 (progn
233 (define-structure-slot-addressor mutex-state-address
234 :structure mutex
235 :slot state)
236 ;; Important: current code assumes these are fixnums or other
237 ;; lisp objects that don't need pinning.
238 (defconstant +lock-free+ 0)
239 (defconstant +lock-taken+ 1)
240 (defconstant +lock-contested+ 2))
242 (defun get-mutex (mutex &optional (new-owner *current-thread*) (waitp t))
243 #!+sb-doc
244 "Acquire MUTEX for NEW-OWNER, which must be a thread or NIL. If
245 NEW-OWNER is NIL, it defaults to the current thread. If WAITP is
246 non-NIL and the mutex is in use, sleep until it is available.
248 Note: using GET-MUTEX to assign a MUTEX to another thread then the
249 current one is not recommended, and liable to be deprecated.
251 GET-MUTEX is not interrupt safe. The correct way to call it is:
253 (WITHOUT-INTERRUPTS
255 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
256 ...)
258 WITHOUT-INTERRUPTS is necessary to avoid an interrupt unwinding the
259 call while the mutex is in an inconsistent state while
260 ALLOW-WITH-INTERRUPTS allows the call to be interrupted from sleep.
262 It is recommended that you use WITH-MUTEX instead of calling GET-MUTEX
263 directly."
264 (declare (type mutex mutex) (optimize (speed 3))
265 #!-sb-thread (ignore waitp))
266 (unless new-owner
267 (setq new-owner *current-thread*))
268 (when (eql new-owner (mutex-%owner mutex))
269 (error "Recursive lock attempt ~S." mutex))
270 #!+sb-thread
271 (progn
272 ;; FIXME: Lutexes do not currently support deadlines, as at least
273 ;; on Darwin pthread_foo_timedbar functions are not supported:
274 ;; this means that we probably need to use the Carbon multiprocessing
275 ;; functions on Darwin.
277 ;; FIXME: This is definitely not interrupt safe: what happens if
278 ;; we get hit (1) during the lutex calls (ok, they may be safe,
279 ;; but has that been checked?) (2) after the lutex call, but
280 ;; before setting the mutex owner.
281 #!+sb-lutex
282 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
283 (if waitp
284 (with-interrupts (%lutex-lock lutex))
285 (%lutex-trylock lutex))))
286 (setf (mutex-%owner mutex) new-owner)
288 #!-sb-lutex
289 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
290 +lock-free+
291 +lock-taken+)))
292 (unless (or (eql +lock-free+ old) (not waitp))
293 (tagbody
294 :retry
295 (when (or (eql +lock-contested+ old)
296 (not (eql +lock-free+
297 (sb!ext:compare-and-swap (mutex-state mutex)
298 +lock-taken+
299 +lock-contested+))))
300 ;; Wait on the contested lock.
301 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
302 (when (= 1 (with-pinned-objects (mutex)
303 (futex-wait (mutex-state-address mutex)
304 (get-lisp-obj-address +lock-contested+)
305 (or to-sec -1)
306 (or to-usec 0))))
307 (signal-deadline))))
308 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
309 +lock-free+
310 +lock-contested+))
311 ;; Did we get it?
312 (unless (eql +lock-free+ old)
313 (go :retry))))
314 (cond ((eql +lock-free+ old)
315 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
316 nil new-owner)))
317 (when prev
318 (bug "Old owner in free mutex: ~S" prev))
320 (waitp
321 (bug "Failed to acquire lock with WAITP."))))))
323 (defun release-mutex (mutex)
324 #!+sb-doc
325 "Release MUTEX by setting it to NIL. Wake up threads waiting for
326 this mutex.
328 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
329 around calls to it.
331 Signals a WARNING is current thread is not the current owner of the
332 mutex."
333 (declare (type mutex mutex))
334 ;; Order matters: set owner to NIL before releasing state.
335 (let* ((self *current-thread*)
336 (old-owner (sb!ext:compare-and-swap (mutex-%owner mutex) self nil)))
337 (unless (eql self old-owner)
338 (warn "Releasing ~S, owned by another thread: ~S" mutex old-owner)
339 (setf (mutex-%owner mutex) nil)))
340 #!+sb-thread
341 (progn
342 #!+sb-lutex
343 (with-lutex-address (lutex (mutex-lutex mutex))
344 (%lutex-unlock lutex))
345 #!-sb-lutex
346 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
347 +lock-taken+ +lock-free+)))
348 (when (eql old +lock-contested+)
349 (sb!ext:compare-and-swap (mutex-state mutex)
350 +lock-contested+ +lock-free+)
351 (with-pinned-objects (mutex)
352 (futex-wake (mutex-state-address mutex) 1))))
353 nil))
355 ;;;; waitqueues/condition variables
357 (defstruct (waitqueue (:constructor %make-waitqueue))
358 #!+sb-doc
359 "Waitqueue type."
360 (name nil :type (or null simple-string))
361 #!+(and sb-lutex sb-thread)
362 (lutex (make-lutex))
363 #!-sb-lutex
364 (data nil))
366 (defun make-waitqueue (&key name)
367 #!+sb-doc
368 "Create a waitqueue."
369 (%make-waitqueue :name name))
371 #!+sb-doc
372 (setf (fdocumentation 'waitqueue-name 'function)
373 "The name of the waitqueue. Setfable.")
375 #!+(and sb-thread (not sb-lutex))
376 (define-structure-slot-addressor waitqueue-data-address
377 :structure waitqueue
378 :slot data)
380 (defun condition-wait (queue mutex)
381 #!+sb-doc
382 "Atomically release MUTEX and enqueue ourselves on QUEUE. Another
383 thread may subsequently notify us using CONDITION-NOTIFY, at which
384 time we reacquire MUTEX and return to the caller."
385 #!-sb-thread (declare (ignore queue))
386 (assert mutex)
387 #!-sb-thread (error "Not supported in unithread builds.")
388 #!+sb-thread
389 (let ((owner (mutex-%owner mutex)))
390 (/show0 "CONDITION-WAITing")
391 #!+sb-lutex
392 (progn
393 ;; FIXME: This doesn't look interrupt safe!
394 (setf (mutex-%owner mutex) nil)
395 (with-lutex-address (queue-lutex-address (waitqueue-lutex queue))
396 (with-lutex-address (mutex-lutex-address (mutex-lutex mutex))
397 (%lutex-wait queue-lutex-address mutex-lutex-address)))
398 (setf (mutex-%owner mutex) owner))
399 #!-sb-lutex
400 (unwind-protect
401 (let ((me *current-thread*))
402 ;; FIXME: should we do something to ensure that the result
403 ;; of this setf is visible to all CPUs?
404 (setf (waitqueue-data queue) me)
405 (release-mutex mutex)
406 ;; Now we go to sleep using futex-wait. If anyone else
407 ;; manages to grab MUTEX and call CONDITION-NOTIFY during
408 ;; this comment, it will change queue->data, and so
409 ;; futex-wait returns immediately instead of sleeping.
410 ;; Ergo, no lost wakeup. We may get spurious wakeups,
411 ;; but that's ok.
412 (multiple-value-bind (to-sec to-usec) (decode-timeout nil)
413 (when (= 1 (with-pinned-objects (queue me)
414 (futex-wait (waitqueue-data-address queue)
415 (get-lisp-obj-address me)
416 (or to-sec -1) ;; our way if saying "no timeout"
417 (or to-usec 0))))
418 (signal-deadline))))
419 ;; If we are interrupted while waiting, we should do these things
420 ;; before returning. Ideally, in the case of an unhandled signal,
421 ;; we should do them before entering the debugger, but this is
422 ;; better than nothing.
423 (get-mutex mutex owner))))
425 (defun condition-notify (queue &optional (n 1))
426 #!+sb-doc
427 "Notify N threads waiting on QUEUE."
428 #!-sb-thread (declare (ignore queue n))
429 #!-sb-thread (error "Not supported in unithread builds.")
430 #!+sb-thread
431 (declare (type (and fixnum (integer 1)) n))
432 (/show0 "Entering CONDITION-NOTIFY")
433 #!+sb-thread
434 (progn
435 #!+sb-lutex
436 (with-lutex-address (lutex (waitqueue-lutex queue))
437 (%lutex-wake lutex n))
438 ;; no problem if >1 thread notifies during the comment in
439 ;; condition-wait: as long as the value in queue-data isn't the
440 ;; waiting thread's id, it matters not what it is
441 ;; XXX we should do something to ensure that the result of this setf
442 ;; is visible to all CPUs
443 #!-sb-lutex
444 (let ((me *current-thread*))
445 (progn
446 (setf (waitqueue-data queue) me)
447 (with-pinned-objects (queue)
448 (futex-wake (waitqueue-data-address queue) n))))))
450 (defun condition-broadcast (queue)
451 #!+sb-doc
452 "Notify all threads waiting on QUEUE."
453 (condition-notify queue
454 ;; On a 64-bit platform truncating M-P-F to an int results
455 ;; in -1, which wakes up only one thread.
456 (ldb (byte 29 0)
457 most-positive-fixnum)))
459 ;;;; semaphores
461 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
462 #!+sb-doc
463 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
464 should be considered an implementation detail, and may change in the
465 future."
466 (name nil :type (or null simple-string))
467 (%count 0 :type (integer 0))
468 (mutex (make-mutex))
469 (queue (make-waitqueue)))
471 (setf (fdocumentation 'semaphore-name 'function)
472 "The name of the semaphore INSTANCE. Setfable.")
474 (declaim (inline semaphore-count))
475 (defun semaphore-count (instance)
476 "Returns the current count of the semaphore INSTANCE."
477 (semaphore-%count instance))
479 (defun make-semaphore (&key name (count 0))
480 #!+sb-doc
481 "Create a semaphore with the supplied COUNT and NAME."
482 (%make-semaphore name count))
484 (defun wait-on-semaphore (semaphore)
485 #!+sb-doc
486 "Decrement the count of SEMAPHORE if the count would not be
487 negative. Else blocks until the semaphore can be decremented."
488 ;; a more direct implementation based directly on futexes should be
489 ;; possible
490 (with-mutex ((semaphore-mutex semaphore))
491 (loop until (> (semaphore-%count semaphore) 0)
492 do (condition-wait (semaphore-queue semaphore) (semaphore-mutex semaphore))
493 finally (decf (semaphore-%count semaphore)))))
495 (defun signal-semaphore (semaphore &optional (n 1))
496 #!+sb-doc
497 "Increment the count of SEMAPHORE by N. If there are threads waiting
498 on this semaphore, then N of them is woken up."
499 (declare (type (integer 1) n))
500 (with-mutex ((semaphore-mutex semaphore))
501 (when (= n (incf (semaphore-%count semaphore) n))
502 (condition-notify (semaphore-queue semaphore) n))))
504 ;;;; job control, independent listeners
506 (defstruct session
507 (lock (make-mutex :name "session lock"))
508 (threads nil)
509 (interactive-threads nil)
510 (interactive-threads-queue (make-waitqueue)))
512 (defvar *session* nil)
514 ;;; The debugger itself tries to acquire the session lock, don't let
515 ;;; funny situations (like getting a sigint while holding the session
516 ;;; lock) occur. At the same time we need to allow interrupts while
517 ;;; *waiting* for the session lock for things like GET-FOREGROUND
518 ;;; to be interruptible.
520 ;;; Take care: we sometimes need to obtain the session lock while holding
521 ;;; on to *ALL-THREADS-LOCK*, so we must _never_ obtain it _after_ getting
522 ;;; a session lock! (Deadlock risk.)
524 ;;; FIXME: It would be good to have ordered locks to ensure invariants like
525 ;;; the above.
526 (defmacro with-session-lock ((session) &body body)
527 `(with-system-mutex ((session-lock ,session) :allow-with-interrupts t)
528 ,@body))
530 (defun new-session ()
531 (make-session :threads (list *current-thread*)
532 :interactive-threads (list *current-thread*)))
534 (defun init-job-control ()
535 (/show0 "Entering INIT-JOB-CONTROL")
536 (setf *session* (new-session))
537 (/show0 "Exiting INIT-JOB-CONTROL"))
539 (defun %delete-thread-from-session (thread session)
540 (with-session-lock (session)
541 (setf (session-threads session)
542 (delete thread (session-threads session))
543 (session-interactive-threads session)
544 (delete thread (session-interactive-threads session)))))
546 (defun call-with-new-session (fn)
547 (%delete-thread-from-session *current-thread* *session*)
548 (let ((*session* (new-session)))
549 (funcall fn)))
551 (defmacro with-new-session (args &body forms)
552 (declare (ignore args)) ;for extensibility
553 (sb!int:with-unique-names (fb-name)
554 `(labels ((,fb-name () ,@forms))
555 (call-with-new-session (function ,fb-name)))))
557 ;;; Remove thread from its session, if it has one.
558 #!+sb-thread
559 (defun handle-thread-exit (thread)
560 (/show0 "HANDLING THREAD EXIT")
561 ;; We're going down, can't handle interrupts sanely anymore.
562 ;; GC remains enabled.
563 (block-deferrable-signals)
564 ;; Lisp-side cleanup
565 (with-all-threads-lock
566 (setf (thread-%alive-p thread) nil)
567 (setf (thread-os-thread thread) nil)
568 (setq *all-threads* (delete thread *all-threads*))
569 (when *session*
570 (%delete-thread-from-session thread *session*)))
571 #!+sb-lutex
572 (without-gcing
573 (/show0 "FREEING MUTEX LUTEX")
574 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
575 (%lutex-destroy lutex))))
577 (defun terminate-session ()
578 #!+sb-doc
579 "Kill all threads in session except for this one. Does nothing if current
580 thread is not the foreground thread."
581 ;; FIXME: threads created in other threads may escape termination
582 (let ((to-kill
583 (with-session-lock (*session*)
584 (and (eq *current-thread*
585 (car (session-interactive-threads *session*)))
586 (session-threads *session*)))))
587 ;; do the kill after dropping the mutex; unwind forms in dying
588 ;; threads may want to do session things
589 (dolist (thread to-kill)
590 (unless (eq thread *current-thread*)
591 ;; terminate the thread but don't be surprised if it has
592 ;; exited in the meantime
593 (handler-case (terminate-thread thread)
594 (interrupt-thread-error ()))))))
596 ;;; called from top of invoke-debugger
597 (defun debugger-wait-until-foreground-thread (stream)
598 "Returns T if thread had been running in background, NIL if it was
599 interactive."
600 (declare (ignore stream))
601 #!-sb-thread nil
602 #!+sb-thread
603 (prog1
604 (with-session-lock (*session*)
605 (not (member *current-thread*
606 (session-interactive-threads *session*))))
607 (get-foreground)))
609 (defun get-foreground ()
610 #!-sb-thread t
611 #!+sb-thread
612 (let ((was-foreground t))
613 (loop
614 (/show0 "Looping in GET-FOREGROUND")
615 (with-session-lock (*session*)
616 (let ((int-t (session-interactive-threads *session*)))
617 (when (eq (car int-t) *current-thread*)
618 (unless was-foreground
619 (format *query-io* "Resuming thread ~A~%" *current-thread*))
620 (return-from get-foreground t))
621 (setf was-foreground nil)
622 (unless (member *current-thread* int-t)
623 (setf (cdr (last int-t))
624 (list *current-thread*)))
625 (condition-wait
626 (session-interactive-threads-queue *session*)
627 (session-lock *session*)))))))
629 (defun release-foreground (&optional next)
630 #!+sb-doc
631 "Background this thread. If NEXT is supplied, arrange for it to
632 have the foreground next."
633 #!-sb-thread (declare (ignore next))
634 #!-sb-thread nil
635 #!+sb-thread
636 (with-session-lock (*session*)
637 (when (rest (session-interactive-threads *session*))
638 (setf (session-interactive-threads *session*)
639 (delete *current-thread* (session-interactive-threads *session*))))
640 (when next
641 (setf (session-interactive-threads *session*)
642 (list* next
643 (delete next (session-interactive-threads *session*)))))
644 (condition-broadcast (session-interactive-threads-queue *session*))))
646 (defun foreground-thread ()
647 (car (session-interactive-threads *session*)))
649 (defun make-listener-thread (tty-name)
650 (assert (probe-file tty-name))
651 (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
652 (out (sb!unix:unix-dup in))
653 (err (sb!unix:unix-dup in)))
654 (labels ((thread-repl ()
655 (sb!unix::unix-setsid)
656 (let* ((sb!impl::*stdin*
657 (make-fd-stream in :input t :buffering :line
658 :dual-channel-p t))
659 (sb!impl::*stdout*
660 (make-fd-stream out :output t :buffering :line
661 :dual-channel-p t))
662 (sb!impl::*stderr*
663 (make-fd-stream err :output t :buffering :line
664 :dual-channel-p t))
665 (sb!impl::*tty*
666 (make-fd-stream err :input t :output t
667 :buffering :line
668 :dual-channel-p t))
669 (sb!impl::*descriptor-handlers* nil))
670 (with-new-session ()
671 (unwind-protect
672 (sb!impl::toplevel-repl nil)
673 (sb!int:flush-standard-output-streams))))))
674 (make-thread #'thread-repl))))
676 ;;;; the beef
678 (defun make-thread (function &key name)
679 #!+sb-doc
680 "Create a new thread of NAME that runs FUNCTION. When the function
681 returns the thread exits. The return values of FUNCTION are kept
682 around and can be retrieved by JOIN-THREAD."
683 #!-sb-thread (declare (ignore function name))
684 #!-sb-thread (error "Not supported in unithread builds.")
685 #!+sb-thread
686 (let* ((thread (%make-thread :name name))
687 (setup-sem (make-semaphore :name "Thread setup semaphore"))
688 (real-function (coerce function 'function))
689 (initial-function
690 (lambda ()
691 ;; In time we'll move some of the binding presently done in C
692 ;; here too.
694 ;; KLUDGE: Here we have a magic list of variables that are
695 ;; not thread-safe for one reason or another. As people
696 ;; report problems with the thread safety of certain
697 ;; variables, (e.g. "*print-case* in multiple threads
698 ;; broken", sbcl-devel 2006-07-14), we add a few more
699 ;; bindings here. The Right Thing is probably some variant
700 ;; of Allegro's *cl-default-special-bindings*, as that is at
701 ;; least accessible to users to secure their own libraries.
702 ;; --njf, 2006-07-15
703 (let* ((*current-thread* thread)
704 (*restart-clusters* nil)
705 (*handler-clusters* (sb!kernel::initial-handler-clusters))
706 (*condition-restarts* nil)
707 (sb!impl::*deadline* nil)
708 (sb!impl::*step-out* nil)
709 ;; internal printer variables
710 (sb!impl::*previous-case* nil)
711 (sb!impl::*previous-readtable-case* nil)
712 (empty (vector))
713 (sb!impl::*merge-sort-temp-vector* empty)
714 (sb!impl::*zap-array-data-temp* empty)
715 (sb!impl::*internal-symbol-output-fun* nil)
716 (sb!impl::*descriptor-handlers* nil)) ; serve-event
717 ;; Binding from C
718 (setf sb!vm:*alloc-signal* *default-alloc-signal*)
719 (setf (thread-os-thread thread) (current-thread-os-thread))
720 (with-mutex ((thread-result-lock thread))
721 (with-all-threads-lock
722 (push thread *all-threads*))
723 (with-session-lock (*session*)
724 (push thread (session-threads *session*)))
725 (setf (thread-%alive-p thread) t)
726 (signal-semaphore setup-sem)
727 ;; can't use handling-end-of-the-world, because that flushes
728 ;; output streams, and we don't necessarily have any (or we
729 ;; could be sharing them)
730 (catch 'sb!impl::toplevel-catcher
731 (catch 'sb!impl::%end-of-the-world
732 (with-simple-restart
733 (terminate-thread
734 (format nil
735 "~~@<Terminate this thread (~A)~~@:>"
736 *current-thread*))
737 (unwind-protect
738 (progn
739 ;; now that most things have a chance to
740 ;; work properly without messing up other
741 ;; threads, it's time to enable signals
742 (sb!unix::reset-signal-mask)
743 (setf (thread-result thread)
744 (cons t
745 (multiple-value-list
746 (funcall real-function)))))
747 (handle-thread-exit thread)))))))
748 (values))))
749 ;; Keep INITIAL-FUNCTION pinned until the child thread is
750 ;; initialized properly.
751 (with-pinned-objects (initial-function)
752 (let ((os-thread
753 (%create-thread
754 (get-lisp-obj-address initial-function))))
755 (when (zerop os-thread)
756 (error "Can't create a new thread"))
757 (wait-on-semaphore setup-sem)
758 thread))))
760 (define-condition join-thread-error (error)
761 ((thread :reader join-thread-error-thread :initarg :thread))
762 #!+sb-doc
763 (:documentation "Joining thread failed.")
764 (:report (lambda (c s)
765 (format s "Joining thread failed: thread ~A ~
766 has not returned normally."
767 (join-thread-error-thread c)))))
769 #!+sb-doc
770 (setf (fdocumentation 'join-thread-error-thread 'function)
771 "The thread that we failed to join.")
773 (defun join-thread (thread &key (default nil defaultp))
774 #!+sb-doc
775 "Suspend current thread until THREAD exits. Returns the result
776 values of the thread function. If the thread does not exit normally,
777 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
778 (with-mutex ((thread-result-lock thread))
779 (cond ((car (thread-result thread))
780 (values-list (cdr (thread-result thread))))
781 (defaultp
782 default)
784 (error 'join-thread-error :thread thread)))))
786 (defun destroy-thread (thread)
787 #!+sb-doc
788 "Deprecated. Same as TERMINATE-THREAD."
789 (terminate-thread thread))
791 (define-condition interrupt-thread-error (error)
792 ((thread :reader interrupt-thread-error-thread :initarg :thread))
793 #!+sb-doc
794 (:documentation "Interrupting thread failed.")
795 (:report (lambda (c s)
796 (format s "Interrupt thread failed: thread ~A has exited."
797 (interrupt-thread-error-thread c)))))
799 #!+sb-doc
800 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
801 "The thread that was not interrupted.")
803 (defmacro with-interruptions-lock ((thread) &body body)
804 `(with-system-mutex ((thread-interruptions-lock ,thread))
805 ,@body))
807 ;; Called from the signal handler in C.
808 (defun run-interruption ()
809 (in-interruption ()
810 (loop
811 (let ((interruption (with-interruptions-lock (*current-thread*)
812 (pop (thread-interruptions *current-thread*)))))
813 (if interruption
814 (with-interrupts
815 (funcall interruption))
816 (return))))))
818 ;; The order of interrupt execution is peculiar. If thread A
819 ;; interrupts thread B with I1, I2 and B for some reason receives I1
820 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
821 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
822 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
823 ;; just one scenario, and the order of thread interrupt execution is
824 ;; undefined.
825 (defun interrupt-thread (thread function)
826 #!+sb-doc
827 "Interrupt the live THREAD and make it run FUNCTION. A moderate
828 degree of care is expected for use of INTERRUPT-THREAD, due to its
829 nature: if you interrupt a thread that was holding important locks
830 then do something that turns out to need those locks, you probably
831 won't like the effect."
832 #!-sb-thread (declare (ignore thread))
833 #!-sb-thread
834 (with-interrupt-bindings
835 (with-interrupts (funcall function)))
836 #!+sb-thread
837 (if (eq thread *current-thread*)
838 (with-interrupt-bindings
839 (with-interrupts (funcall function)))
840 (let ((os-thread (thread-os-thread thread)))
841 (cond ((not os-thread)
842 (error 'interrupt-thread-error :thread thread))
844 (with-interruptions-lock (thread)
845 (push function (thread-interruptions thread)))
846 (when (minusp (signal-interrupt-thread os-thread))
847 (error 'interrupt-thread-error :thread thread)))))))
849 (defun terminate-thread (thread)
850 #!+sb-doc
851 "Terminate the thread identified by THREAD, by causing it to run
852 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
853 (interrupt-thread thread 'sb!ext:quit))
855 (define-alien-routine "thread_yield" int)
857 #!+sb-doc
858 (setf (fdocumentation 'thread-yield 'function)
859 "Yield the processor to other threads.")
861 ;;; internal use only. If you think you need to use these, either you
862 ;;; are an SBCL developer, are doing something that you should discuss
863 ;;; with an SBCL developer first, or are doing something that you
864 ;;; should probably discuss with a professional psychiatrist first
865 #!+sb-thread
866 (progn
867 (defun %thread-sap (thread)
868 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t))))
869 (target (thread-os-thread thread)))
870 (loop
871 (when (sap= thread-sap (int-sap 0)) (return nil))
872 (let ((os-thread (sap-ref-word thread-sap
873 (* sb!vm:n-word-bytes
874 sb!vm::thread-os-thread-slot))))
875 (when (= os-thread target) (return thread-sap))
876 (setf thread-sap
877 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
878 sb!vm::thread-next-slot)))))))
880 (defun %symbol-value-in-thread (symbol thread)
881 (tagbody
882 ;; Prevent the dead from dying completely while we look for the TLS area...
883 (with-all-threads-lock
884 (if (thread-alive-p thread)
885 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
886 (tl-val (sap-ref-word (%thread-sap thread) offset)))
887 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
888 (go :unbound)
889 (return-from %symbol-value-in-thread (values (make-lisp-obj tl-val) t))))
890 (return-from %symbol-value-in-thread (values nil nil))))
891 :unbound
892 (error "Cannot read thread-local symbol value: ~S unbound in ~S" symbol thread)))
894 (defun %set-symbol-value-in-thread (symbol thread value)
895 (tagbody
896 (with-pinned-objects (value)
897 ;; Prevent the dead from dying completely while we look for the TLS area...
898 (with-all-threads-lock
899 (if (thread-alive-p thread)
900 (let* ((offset (* sb!vm:n-word-bytes (sb!vm::symbol-tls-index symbol)))
901 (sap (%thread-sap thread))
902 (tl-val (sap-ref-word sap offset)))
903 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
904 (go :unbound)
905 (setf (sap-ref-word sap offset) (get-lisp-obj-address value)))
906 (return-from %set-symbol-value-in-thread (values value t)))
907 (return-from %set-symbol-value-in-thread (values nil nil)))))
908 :unbound
909 (error "Cannot set thread-local symbol value: ~S unbound in ~S" symbol thread))))
911 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
912 (sb!vm::locked-symbol-global-value-add symbol-name delta))
914 ;;; Stepping
916 (defun thread-stepping ()
917 (make-lisp-obj
918 (sap-ref-word (current-thread-sap)
919 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
921 (defun (setf thread-stepping) (value)
922 (setf (sap-ref-word (current-thread-sap)
923 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
924 (get-lisp-obj-address value)))