1.0.10.49: deadline refinements
[sbcl/simd.git] / src / code / target-thread.lisp
blob38549a3d55592328a111101d3fc572d867ae0e86
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 (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
47 ;; identity
49 thread)
51 (defun thread-alive-p (thread)
52 #!+sb-doc
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 ()
66 #!+sb-doc
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 ()
77 (sap-int
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"
83 :%alive-p t
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))))
91 ;;;;
93 #!+sb-thread
94 (progn
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
98 ;; implementations.
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"
106 void)
108 #!+sb-lutex
109 (progn
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)))
142 ,@body))))
144 (defun make-lutex ()
145 (/show0 "Entering MAKE-LUTEX")
146 ;; Suppress GC until the lutex has been properly registered with
147 ;; the GC.
148 (without-gcing
149 (let ((lutex (sb!vm::%make-lutex)))
150 (/show0 "LUTEX=..")
151 (/hexstr lutex)
152 (with-lutex-address (lutex lutex)
153 (%lutex-init lutex))
154 lutex))))
156 #!-sb-lutex
157 (progn
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)
165 (with-interrupts
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))
173 #!-sb-thread
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)))
179 #!+sb-thread
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)))
191 (when old
192 (when (eq old new)
193 (error "Recursive lock attempt on ~S." spinlock))
194 #!+sb-thread
195 (flet ((cas ()
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.
201 (loop
202 (loop repeat 128 do (cas)) ; 128 is arbitrary here
203 (sb!unix::%check-interrupts))
204 (loop (cas)))))
207 (defun release-spinlock (spinlock)
208 (declare (optimize (speed 3) (safety 0)))
209 (setf (spinlock-value spinlock) nil)
210 nil)
212 ;;;; mutexes
214 #!+sb-doc
215 (setf (fdocumentation 'make-mutex 'function)
216 "Create a mutex."
217 (fdocumentation 'mutex-name 'function)
218 "The name of the mutex. Setfable.")
220 #!+(and sb-thread (not sb-lutex))
221 (progn
222 (define-structure-slot-addressor mutex-state-address
223 :structure mutex
224 :slot state)
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))
232 #!+sb-doc
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:
242 (WITHOUT-INTERRUPTS
244 (ALLOW-WITH-INTERRUPTS (GET-MUTEX ...))
245 ...)
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
252 directly."
253 (declare (type mutex mutex) (optimize (speed 3))
254 #!-sb-thread (ignore waitp))
255 (unless new-owner
256 (setq new-owner *current-thread*))
257 (when (eql new-owner (mutex-%owner mutex))
258 (error "Recursive lock attempt ~S." mutex))
259 #!+sb-thread
260 (progn
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.
270 #!+sb-lutex
271 (when (zerop (with-lutex-address (lutex (mutex-lutex mutex))
272 (if waitp
273 (with-interrupts (%lutex-lock lutex))
274 (%lutex-trylock lutex))))
275 (setf (mutex-%owner mutex) new-owner)
277 #!-sb-lutex
278 (let ((old (sb!ext:compare-and-swap (mutex-state mutex)
279 +lock-free+
280 +lock-taken+)))
281 (unless (or (eql +lock-free+ old) (not waitp))
282 (tagbody
283 :retry
284 (when (or (eql +lock-contested+ old)
285 (not (eql +lock-free+
286 (sb!ext:compare-and-swap (mutex-state mutex)
287 +lock-taken+
288 +lock-contested+))))
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+)
294 (or to-sec -1)
295 (or to-usec 0))))
296 (signal-deadline))))
297 (setf old (sb!ext:compare-and-swap (mutex-state mutex)
298 +lock-free+
299 +lock-contested+))
300 ;; Did we get it?
301 (unless (eql +lock-free+ old)
302 (go :retry))))
303 (cond ((eql +lock-free+ old)
304 (let ((prev (sb!ext:compare-and-swap (mutex-%owner mutex)
305 nil new-owner)))
306 (when prev
307 (bug "Old owner in free mutex: ~S" prev))
309 (waitp
310 (bug "Failed to acquire lock with WAITP."))))))
312 (defun release-mutex (mutex)
313 #!+sb-doc
314 "Release MUTEX by setting it to NIL. Wake up threads waiting for
315 this mutex.
317 RELEASE-MUTEX is not interrupt safe: interrupts should be disabled
318 around calls to it.
320 Signals a WARNING is current thread is not the current owner of the
321 mutex."
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)))
329 #!+sb-thread
330 (progn
331 #!+sb-lutex
332 (with-lutex-address (lutex (mutex-lutex mutex))
333 (%lutex-unlock lutex))
334 #!-sb-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))))
342 nil))
344 ;;;; waitqueues/condition variables
346 (defstruct (waitqueue (:constructor %make-waitqueue))
347 #!+sb-doc
348 "Waitqueue type."
349 (name nil :type (or null simple-string))
350 #!+(and sb-lutex sb-thread)
351 (lutex (make-lutex))
352 #!-sb-lutex
353 (data nil))
355 (defun make-waitqueue (&key name)
356 #!+sb-doc
357 "Create a waitqueue."
358 (%make-waitqueue :name name))
360 #!+sb-doc
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
366 :structure waitqueue
367 :slot data)
369 (defun condition-wait (queue mutex)
370 #!+sb-doc
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))
375 (assert mutex)
376 #!-sb-thread (error "Not supported in unithread builds.")
377 #!+sb-thread
378 (let ((owner (mutex-%owner mutex)))
379 (/show0 "CONDITION-WAITing")
380 #!+sb-lutex
381 (progn
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))
388 #!-sb-lutex
389 (unwind-protect
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,
400 ;; but that's ok.
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"
406 (or to-usec 0))))
407 (signal-deadline))))
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))
415 #!+sb-doc
416 "Notify N threads waiting on QUEUE."
417 #!-sb-thread (declare (ignore queue n))
418 #!-sb-thread (error "Not supported in unithread builds.")
419 #!+sb-thread
420 (declare (type (and fixnum (integer 1)) n))
421 (/show0 "Entering CONDITION-NOTIFY")
422 #!+sb-thread
423 (progn
424 #!+sb-lutex
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
432 #!-sb-lutex
433 (let ((me *current-thread*))
434 (progn
435 (setf (waitqueue-data queue) me)
436 (with-pinned-objects (queue)
437 (futex-wake (waitqueue-data-address queue) n))))))
439 (defun condition-broadcast (queue)
440 #!+sb-doc
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.
445 (ldb (byte 29 0)
446 most-positive-fixnum)))
448 ;;;; semaphores
450 (defstruct (semaphore (:constructor %make-semaphore (name %count)))
451 #!+sb-doc
452 "Semaphore type. The fact that a SEMAPHORE is a STRUCTURE-OBJECT
453 should be considered an implementation detail, and may change in the
454 future."
455 (name nil :type (or null simple-string))
456 (%count 0 :type (integer 0))
457 (mutex (make-mutex))
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))
469 #!+sb-doc
470 "Create a semaphore with the supplied COUNT and NAME."
471 (%make-semaphore name count))
473 (defun wait-on-semaphore (semaphore)
474 #!+sb-doc
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
478 ;; possible
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))
485 #!+sb-doc
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
495 (defstruct session
496 (lock (make-mutex :name "session lock"))
497 (threads nil)
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
505 ;;; lock) occur
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)))
528 (funcall fn)))
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.
537 #!+sb-thread
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)
543 ;; Lisp-side cleanup
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*))
548 (when *session*
549 (%delete-thread-from-session thread *session*)))
550 #!+sb-lutex
551 (without-gcing
552 (/show0 "FREEING MUTEX LUTEX")
553 (with-lutex-address (lutex (mutex-lutex (thread-interruptions-lock thread)))
554 (%lutex-destroy lutex))))
556 (defun terminate-session ()
557 #!+sb-doc
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
561 (let ((to-kill
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
578 interactive."
579 (declare (ignore stream))
580 #!-sb-thread nil
581 #!+sb-thread
582 (prog1
583 (with-session-lock (*session*)
584 (not (member *current-thread*
585 (session-interactive-threads *session*))))
586 (get-foreground)))
588 (defun get-foreground ()
589 #!-sb-thread t
590 #!+sb-thread
591 (let ((was-foreground t))
592 (loop
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*)))
604 (condition-wait
605 (session-interactive-threads-queue *session*)
606 (session-lock *session*)))))))
608 (defun release-foreground (&optional next)
609 #!+sb-doc
610 "Background this thread. If NEXT is supplied, arrange for it to
611 have the foreground next."
612 #!-sb-thread (declare (ignore next))
613 #!-sb-thread nil
614 #!+sb-thread
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*))))
619 (when next
620 (setf (session-interactive-threads *session*)
621 (list* next
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
637 :dual-channel-p t))
638 (sb!impl::*stdout*
639 (make-fd-stream out :output t :buffering :line
640 :dual-channel-p t))
641 (sb!impl::*stderr*
642 (make-fd-stream err :output t :buffering :line
643 :dual-channel-p t))
644 (sb!impl::*tty*
645 (make-fd-stream err :input t :output t
646 :buffering :line
647 :dual-channel-p t))
648 (sb!impl::*descriptor-handlers* nil))
649 (with-new-session ()
650 (unwind-protect
651 (sb!impl::toplevel-repl nil)
652 (sb!int:flush-standard-output-streams))))))
653 (make-thread #'thread-repl))))
655 ;;;; the beef
657 (defun make-thread (function &key name)
658 #!+sb-doc
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.")
664 #!+sb-thread
665 (let* ((thread (%make-thread :name name))
666 (setup-sem (make-semaphore :name "Thread setup semaphore"))
667 (real-function (coerce function 'function))
668 (initial-function
669 (lambda ()
670 ;; In time we'll move some of the binding presently done in C
671 ;; here too.
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.
681 ;; --njf, 2006-07-15
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)
691 (sb!impl::*merge-sort-temp-vector* (vector)) ; keep these small!
692 (sb!impl::*zap-array-data-temp* (vector)) ;
693 (sb!impl::*internal-symbol-output-fun* nil)
694 (sb!impl::*descriptor-handlers* nil)) ; serve-event
695 (setf (thread-os-thread thread) (current-thread-sap-id))
696 (with-mutex ((thread-result-lock thread))
697 (with-all-threads-lock
698 (push thread *all-threads*))
699 (with-session-lock (*session*)
700 (push thread (session-threads *session*)))
701 (setf (thread-%alive-p thread) t)
702 (signal-semaphore setup-sem)
703 ;; can't use handling-end-of-the-world, because that flushes
704 ;; output streams, and we don't necessarily have any (or we
705 ;; could be sharing them)
706 (catch 'sb!impl::toplevel-catcher
707 (catch 'sb!impl::%end-of-the-world
708 (with-simple-restart
709 (terminate-thread
710 (format nil
711 "~~@<Terminate this thread (~A)~~@:>"
712 *current-thread*))
713 (unwind-protect
714 (progn
715 ;; now that most things have a chance to
716 ;; work properly without messing up other
717 ;; threads, it's time to enable signals
718 (sb!unix::reset-signal-mask)
719 (setf (thread-result thread)
720 (cons t
721 (multiple-value-list
722 (funcall real-function)))))
723 (handle-thread-exit thread)))))))
724 (values))))
725 ;; Keep INITIAL-FUNCTION pinned until the child thread is
726 ;; initialized properly.
727 (with-pinned-objects (initial-function)
728 (let ((os-thread
729 (%create-thread
730 (get-lisp-obj-address initial-function))))
731 (when (zerop os-thread)
732 (error "Can't create a new thread"))
733 (wait-on-semaphore setup-sem)
734 thread))))
736 (define-condition join-thread-error (error)
737 ((thread :reader join-thread-error-thread :initarg :thread))
738 #!+sb-doc
739 (:documentation "Joining thread failed.")
740 (:report (lambda (c s)
741 (format s "Joining thread failed: thread ~A ~
742 has not returned normally."
743 (join-thread-error-thread c)))))
745 #!+sb-doc
746 (setf (fdocumentation 'join-thread-error-thread 'function)
747 "The thread that we failed to join.")
749 (defun join-thread (thread &key (default nil defaultp))
750 #!+sb-doc
751 "Suspend current thread until THREAD exits. Returns the result
752 values of the thread function. If the thread does not exit normally,
753 return DEFAULT if given or else signal JOIN-THREAD-ERROR."
754 (with-mutex ((thread-result-lock thread))
755 (cond ((car (thread-result thread))
756 (values-list (cdr (thread-result thread))))
757 (defaultp
758 default)
760 (error 'join-thread-error :thread thread)))))
762 (defun destroy-thread (thread)
763 #!+sb-doc
764 "Deprecated. Same as TERMINATE-THREAD."
765 (terminate-thread thread))
767 (define-condition interrupt-thread-error (error)
768 ((thread :reader interrupt-thread-error-thread :initarg :thread))
769 #!+sb-doc
770 (:documentation "Interrupting thread failed.")
771 (:report (lambda (c s)
772 (format s "Interrupt thread failed: thread ~A has exited."
773 (interrupt-thread-error-thread c)))))
775 #!+sb-doc
776 (setf (fdocumentation 'interrupt-thread-error-thread 'function)
777 "The thread that was not interrupted.")
779 (defmacro with-interruptions-lock ((thread) &body body)
780 `(call-with-system-mutex (lambda () ,@body) (thread-interruptions-lock ,thread)))
782 ;; Called from the signal handler in C.
783 (defun run-interruption ()
784 (in-interruption ()
785 (loop
786 (let ((interruption (with-interruptions-lock (*current-thread*)
787 (pop (thread-interruptions *current-thread*)))))
788 (if interruption
789 (with-interrupts
790 (funcall interruption))
791 (return))))))
793 ;; The order of interrupt execution is peculiar. If thread A
794 ;; interrupts thread B with I1, I2 and B for some reason receives I1
795 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
796 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
797 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
798 ;; just one scenario, and the order of thread interrupt execution is
799 ;; undefined.
800 (defun interrupt-thread (thread function)
801 #!+sb-doc
802 "Interrupt the live THREAD and make it run FUNCTION. A moderate
803 degree of care is expected for use of INTERRUPT-THREAD, due to its
804 nature: if you interrupt a thread that was holding important locks
805 then do something that turns out to need those locks, you probably
806 won't like the effect."
807 #!-sb-thread (declare (ignore thread))
808 #!-sb-thread
809 (with-interrupt-bindings
810 (with-interrupts (funcall function)))
811 #!+sb-thread
812 (if (eq thread *current-thread*)
813 (with-interrupt-bindings
814 (with-interrupts (funcall function)))
815 (let ((os-thread (thread-os-thread thread)))
816 (cond ((not os-thread)
817 (error 'interrupt-thread-error :thread thread))
819 (with-interruptions-lock (thread)
820 (push function (thread-interruptions thread)))
821 (when (minusp (signal-interrupt-thread os-thread))
822 (error 'interrupt-thread-error :thread thread)))))))
824 (defun terminate-thread (thread)
825 #!+sb-doc
826 "Terminate the thread identified by THREAD, by causing it to run
827 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
828 (interrupt-thread thread 'sb!ext:quit))
830 ;;; internal use only. If you think you need to use this, either you
831 ;;; are an SBCL developer, are doing something that you should discuss
832 ;;; with an SBCL developer first, or are doing something that you
833 ;;; should probably discuss with a professional psychiatrist first
834 #!+sb-thread
835 (defun thread-sap-for-id (id)
836 (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
837 (loop
838 (when (sap= thread-sap (int-sap 0)) (return nil))
839 (let ((os-thread (sap-ref-word thread-sap
840 (* sb!vm:n-word-bytes
841 sb!vm::thread-os-thread-slot))))
842 (when (= os-thread id) (return thread-sap))
843 (setf thread-sap
844 (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
845 sb!vm::thread-next-slot)))))))
847 #!+sb-thread
848 (defun symbol-value-in-thread (symbol thread-sap)
849 (let* ((index (sb!vm::symbol-tls-index symbol))
850 (tl-val (sap-ref-word thread-sap
851 (* sb!vm:n-word-bytes index))))
852 (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
853 (sb!vm::symbol-global-value symbol)
854 (make-lisp-obj tl-val))))
856 (defun sb!vm::locked-symbol-global-value-add (symbol-name delta)
857 (sb!vm::locked-symbol-global-value-add symbol-name delta))
859 ;;; Stepping
861 (defun thread-stepping ()
862 (make-lisp-obj
863 (sap-ref-word (current-thread-sap)
864 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))))
866 (defun (setf thread-stepping) (value)
867 (setf (sap-ref-word (current-thread-sap)
868 (* sb!vm::thread-stepping-slot sb!vm:n-word-bytes))
869 (get-lisp-obj-address value)))