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