0.9.5.31:
[sbcl.git] / src / code / target-thread.lisp
1 ;;;; support for threads in the target machine
2
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.
11
12 (in-package "SB!THREAD")
13
14 ;;; set the doc here because in early-thread FDOCUMENTATION is not
15 ;;; available, yet
16 #!+sb-doc
17 (setf (sb!kernel:fdocumentation '*current-thread* 'variable)
18       "Bound in each thread to the thread itself.")
19
20 (defstruct (thread (:constructor %make-thread))
21   #!+sb-doc
22   "Thread type. Do not rely on threads being structs as it may change
23 in future versions."
24   name
25   %alive-p
26   os-thread
27   interruptions
28   (interruptions-lock (make-mutex :name "thread interruptions lock")))
29
30 #!+sb-doc
31 (setf (sb!kernel:fdocumentation 'thread-name 'function)
32       "The name of the thread. Setfable.")
33
34 (def!method print-object ((thread thread) stream)
35   (if (thread-name thread)
36       (print-unreadable-object (thread stream :type t :identity t)
37         (prin1 (thread-name thread) stream))
38       (print-unreadable-object (thread stream :type t :identity t)
39         ;; body is empty => there is only one space between type and
40         ;; identity
41         ))
42   thread)
43
44 (defun thread-alive-p (thread)
45   #!+sb-doc
46   "Check if THREAD is running."
47   (thread-%alive-p thread))
48
49 ;; A thread is eligible for gc iff it has finished and there are no
50 ;; more references to it. This list is supposed to keep a reference to
51 ;; all running threads.
52 (defvar *all-threads* ())
53 (defvar *all-threads-lock* (make-mutex :name "all threads lock"))
54
55 (defun list-all-threads ()
56   #!+sb-doc
57   "Return a list of the live threads."
58   (with-mutex (*all-threads-lock*)
59     (copy-list *all-threads*)))
60
61 (declaim (inline current-thread-sap))
62 (defun current-thread-sap ()
63   (sb!vm::current-thread-offset-sap sb!vm::thread-this-slot))
64
65 (declaim (inline current-thread-sap-id))
66 (defun current-thread-sap-id ()
67   (sap-int
68    (sb!vm::current-thread-offset-sap sb!vm::thread-os-thread-slot)))
69
70 (defun init-initial-thread ()
71   (let ((initial-thread (%make-thread :name "initial thread"
72                                       :%alive-p t
73                                       :os-thread (current-thread-sap-id))))
74     (setq *current-thread* initial-thread)
75     ;; Either *all-threads* is empty or it contains exactly one thread
76     ;; in case we are in reinit since saving core with multiple
77     ;; threads doesn't work.
78     (setq *all-threads* (list initial-thread))))
79
80 ;;;;
81
82 #!+sb-thread
83 (progn
84   ;; FIXME it would be good to define what a thread id is or isn't
85   ;; (our current assumption is that it's a fixnum).  It so happens
86   ;; that on Linux it's a pid, but it might not be on posix thread
87   ;; implementations.
88   (define-alien-routine ("create_thread" %create-thread)
89       unsigned-long (lisp-fun-address unsigned-long))
90
91   (define-alien-routine "signal_interrupt_thread"
92       integer (os-thread unsigned-long))
93
94   (define-alien-routine "block_blockable_signals"
95       void)
96
97   (declaim (inline futex-wait futex-wake))
98
99   (sb!alien:define-alien-routine "futex_wait"
100       int (word unsigned-long) (old-value unsigned-long))
101
102   (sb!alien:define-alien-routine "futex_wake"
103       int (word unsigned-long) (n unsigned-long)))
104
105 ;;; used by debug-int.lisp to access interrupt contexts
106 #!-(and sb-fluid sb-thread) (declaim (inline sb!vm::current-thread-offset-sap))
107 #!-sb-thread
108 (defun sb!vm::current-thread-offset-sap (n)
109   (declare (type (unsigned-byte 27) n))
110   (sap-ref-sap (alien-sap (extern-alien "all_threads" (* t)))
111                (* n sb!vm:n-word-bytes)))
112
113 ;;;; spinlocks
114
115 (defstruct spinlock
116   #!+sb-doc
117   "Spinlock type."
118   (name nil :type (or null simple-string))
119   (value 0))
120
121 (declaim (inline get-spinlock release-spinlock))
122
123 ;;; The bare 2 here and below are offsets of the slots in the struct.
124 ;;; There ought to be some better way to get these numbers
125 (defun get-spinlock (spinlock new-value)
126   (declare (optimize (speed 3) (safety 0))
127            #!-sb-thread
128            (ignore spinlock new-value))
129   ;; %instance-set-conditional can test for 0 (which is a fixnum) and
130   ;; store any value
131   #!+sb-thread
132   (loop until
133         (eql (sb!vm::%instance-set-conditional spinlock 2 0 new-value) 0)))
134
135 (defun release-spinlock (spinlock)
136   (declare (optimize (speed 3) (safety 0))
137            #!-sb-thread (ignore spinlock))
138   ;; %instance-set-conditional cannot compare arbitrary objects
139   ;; meaningfully, so
140   ;; (sb!vm::%instance-set-conditional spinlock 2 our-value 0)
141   ;; does not work for bignum thread ids.
142   #!+sb-thread
143   (sb!vm::%instance-set spinlock 2 0))
144
145 (defmacro with-spinlock ((spinlock) &body body)
146   (sb!int:with-unique-names (lock)
147     `(let ((,lock ,spinlock))
148       (get-spinlock ,lock *current-thread*)
149       (unwind-protect
150            (progn ,@body)
151         (release-spinlock ,lock)))))
152
153 ;;;; mutexes
154
155 (defstruct mutex
156   #!+sb-doc
157   "Mutex type."
158   (name nil :type (or null simple-string))
159   (value nil))
160
161 #!+sb-doc
162 (setf (sb!kernel:fdocumentation 'make-mutex 'function)
163       "Create a mutex."
164       (sb!kernel:fdocumentation 'mutex-name 'function)
165       "The name of the mutex. Setfable."
166       (sb!kernel:fdocumentation 'mutex-value 'function)
167       "The value of the mutex. NIL if the mutex is free. Setfable.")
168
169 #!+sb-thread
170 (declaim (inline mutex-value-address))
171 #!+sb-thread
172 (defun mutex-value-address (mutex)
173   (declare (optimize (speed 3)))
174   (sb!ext:truly-the
175    sb!vm:word
176    (+ (sb!kernel:get-lisp-obj-address mutex)
177       (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
178
179 (defun get-mutex (mutex &optional (new-value *current-thread*) (wait-p t))
180   #!+sb-doc
181   "Acquire MUTEX, setting it to NEW-VALUE or some suitable default
182 value if NIL.  If WAIT-P is non-NIL and the mutex is in use, sleep
183 until it is available"
184   (declare (type mutex mutex) (optimize (speed 3)))
185   (unless new-value
186     (setq new-value *current-thread*))
187   #!-sb-thread
188   (let ((old-value (mutex-value mutex)))
189     (when (and old-value wait-p)
190       (error "In unithread mode, mutex ~S was requested with WAIT-P ~S and ~
191               new-value ~S, but has already been acquired (with value ~S)."
192              mutex wait-p new-value old-value))
193     (setf (mutex-value mutex) new-value)
194     t)
195   #!+sb-thread
196   (let (old)
197     (when (eql new-value (mutex-value mutex))
198       (warn "recursive lock attempt ~S~%" mutex)
199       (format *debug-io* "Thread: ~A~%" *current-thread*)
200       (sb!debug:backtrace most-positive-fixnum *debug-io*)
201       (force-output *debug-io*))
202     (loop
203      (unless
204          (setf old (sb!vm::%instance-set-conditional mutex 2 nil new-value))
205        (return t))
206      (unless wait-p (return nil))
207      (futex-wait (mutex-value-address mutex)
208                  (sb!kernel:get-lisp-obj-address old)))))
209
210 (defun release-mutex (mutex)
211   #!+sb-doc
212   "Release MUTEX by setting it to NIL. Wake up threads waiting for
213 this mutex."
214   (declare (type mutex mutex))
215   (setf (mutex-value mutex) nil)
216   #!+sb-thread
217   (futex-wake (mutex-value-address mutex) 1))
218
219 ;;;; waitqueues/condition variables
220
221 (defstruct (waitqueue (:constructor %make-waitqueue))
222   #!+sb-doc
223   "Waitqueue type."
224   (name nil :type (or null simple-string))
225   (data nil))
226
227 (defun make-waitqueue (&key name)
228   #!+sb-doc
229   "Create a waitqueue."
230   (%make-waitqueue :name name))
231
232 #!+sb-doc
233 (setf (sb!kernel:fdocumentation 'waitqueue-name 'function)
234       "The name of the waitqueue. Setfable.")
235
236 #!+sb-thread
237 (declaim (inline waitqueue-data-address))
238 #!+sb-thread
239 (defun waitqueue-data-address (waitqueue)
240   (declare (optimize (speed 3)))
241   (sb!ext:truly-the
242    sb!vm:word
243    (+ (sb!kernel:get-lisp-obj-address waitqueue)
244       (- (* 3 sb!vm:n-word-bytes) sb!vm:instance-pointer-lowtag))))
245
246 (defun condition-wait (queue mutex)
247   #!+sb-doc
248   "Atomically release MUTEX and enqueue ourselves on QUEUE.  Another
249 thread may subsequently notify us using CONDITION-NOTIFY, at which
250 time we reacquire MUTEX and return to the caller."
251   #!-sb-thread (declare (ignore queue))
252   (assert mutex)
253   #!-sb-thread (error "Not supported in unithread builds.")
254   #!+sb-thread
255   (let ((value (mutex-value mutex)))
256     (unwind-protect
257          (let ((me *current-thread*))
258            ;; XXX we should do something to ensure that the result of this setf
259            ;; is visible to all CPUs
260            (setf (waitqueue-data queue) me)
261            (release-mutex mutex)
262            ;; Now we go to sleep using futex-wait.  If anyone else
263            ;; manages to grab MUTEX and call CONDITION-NOTIFY during
264            ;; this comment, it will change queue->data, and so
265            ;; futex-wait returns immediately instead of sleeping.
266            ;; Ergo, no lost wakeup
267            (futex-wait (waitqueue-data-address queue)
268                        (sb!kernel:get-lisp-obj-address me)))
269       ;; If we are interrupted while waiting, we should do these things
270       ;; before returning.  Ideally, in the case of an unhandled signal,
271       ;; we should do them before entering the debugger, but this is
272       ;; better than nothing.
273       (get-mutex mutex value))))
274
275 (defun condition-notify (queue &optional (n 1))
276   #!+sb-doc
277   "Notify N threads waiting on QUEUE."
278   #!-sb-thread (declare (ignore queue n))
279   #!-sb-thread (error "Not supported in unithread builds.")
280   #!+sb-thread
281   (declare (type (and fixnum (integer 1)) n))
282   #!+sb-thread
283   (let ((me *current-thread*))
284     ;; no problem if >1 thread notifies during the comment in
285     ;; condition-wait: as long as the value in queue-data isn't the
286     ;; waiting thread's id, it matters not what it is
287     ;; XXX we should do something to ensure that the result of this setf
288     ;; is visible to all CPUs
289     (setf (waitqueue-data queue) me)
290     (futex-wake (waitqueue-data-address queue) n)))
291
292 (defun condition-broadcast (queue)
293   #!+sb-doc
294   "Notify all threads waiting on QUEUE."
295   (condition-notify queue most-positive-fixnum))
296
297 ;;;; semaphores
298
299 (defstruct (semaphore (:constructor %make-semaphore))
300   #!+sb-doc
301   "Semaphore type."
302   (name nil :type (or null simple-string))
303   (count 0 :type (integer 0))
304   (mutex (make-mutex))
305   (queue (make-waitqueue)))
306
307 (defun make-semaphore (&key name (count 0))
308   #!+sb-doc
309   "Create a semaphore with the supplied COUNT."
310   (%make-semaphore :name name :count count))
311
312 (setf (sb!kernel:fdocumentation 'semaphore-name 'function)
313       "The name of the semaphore. Setfable.")
314
315 (defun wait-on-semaphore (sem)
316   #!+sb-doc
317   "Decrement the count of SEM if the count would not be negative. Else
318 block until the semaphore can be decremented."
319   ;; a more direct implementation based directly on futexes should be
320   ;; possible
321   (with-mutex ((semaphore-mutex sem))
322     (loop until (> (semaphore-count sem) 0)
323           do (condition-wait (semaphore-queue sem) (semaphore-mutex sem))
324           finally (decf (semaphore-count sem)))))
325
326 (defun signal-semaphore (sem &optional (n 1))
327   #!+sb-doc
328   "Increment the count of SEM by N. If there are threads waiting on
329 this semaphore, then N of them is woken up."
330   (declare (type (and fixnum (integer 1)) n))
331   (with-mutex ((semaphore-mutex sem))
332     (when (= n (incf (semaphore-count sem) n))
333       (condition-notify (semaphore-queue sem) n))))
334
335 ;;;; job control, independent listeners
336
337 (defstruct session
338   (lock (make-mutex :name "session lock"))
339   (threads nil)
340   (interactive-threads nil)
341   (interactive-threads-queue (make-waitqueue)))
342
343 (defvar *session* nil)
344
345 ;;; the debugger itself tries to acquire the session lock, don't let
346 ;;; funny situations (like getting a sigint while holding the session
347 ;;; lock) occur
348 (defmacro with-session-lock ((session) &body body)
349   #!-sb-thread (declare (ignore session))
350   #!-sb-thread
351   `(locally ,@body)
352   #!+sb-thread
353   `(without-interrupts
354     (with-mutex ((session-lock ,session))
355       ,@body)))
356
357 (defun new-session ()
358   (make-session :threads (list *current-thread*)
359                 :interactive-threads (list *current-thread*)))
360
361 (defun init-job-control ()
362   (setf *session* (new-session)))
363
364 (defun %delete-thread-from-session (thread session)
365   (with-session-lock (session)
366     (setf (session-threads session)
367           (delete thread (session-threads session))
368           (session-interactive-threads session)
369           (delete thread (session-interactive-threads session)))))
370
371 (defun call-with-new-session (fn)
372   (%delete-thread-from-session *current-thread* *session*)
373   (let ((*session* (new-session)))
374     (funcall fn)))
375
376 (defmacro with-new-session (args &body forms)
377   (declare (ignore args))               ;for extensibility
378   (sb!int:with-unique-names (fb-name)
379     `(labels ((,fb-name () ,@forms))
380       (call-with-new-session (function ,fb-name)))))
381
382 ;;; Remove thread from its session, if it has one.
383 #!+sb-thread
384 (defun handle-thread-exit (thread)
385   (with-mutex (*all-threads-lock*)
386     (setq *all-threads* (delete thread *all-threads*)))
387   (when *session*
388     (%delete-thread-from-session thread *session*)))
389
390 (defun terminate-session ()
391   #!+sb-doc
392   "Kill all threads in session except for this one.  Does nothing if current
393 thread is not the foreground thread."
394   ;; FIXME: threads created in other threads may escape termination
395   (let ((to-kill
396          (with-session-lock (*session*)
397            (and (eq *current-thread*
398                     (car (session-interactive-threads *session*)))
399                 (session-threads *session*)))))
400     ;; do the kill after dropping the mutex; unwind forms in dying
401     ;; threads may want to do session things
402     (dolist (thread to-kill)
403       (unless (eq thread *current-thread*)
404         ;; terminate the thread but don't be surprised if it has
405         ;; exited in the meantime
406         (handler-case (terminate-thread thread)
407           (interrupt-thread-error ()))))))
408
409 ;;; called from top of invoke-debugger
410 (defun debugger-wait-until-foreground-thread (stream)
411   "Returns T if thread had been running in background, NIL if it was
412 interactive."
413   (declare (ignore stream))
414   #!-sb-thread nil
415   #!+sb-thread
416   (prog1
417       (with-session-lock (*session*)
418         (not (member *current-thread*
419                      (session-interactive-threads *session*))))
420     (get-foreground)))
421
422 (defun get-foreground ()
423   #!-sb-thread t
424   #!+sb-thread
425   (let ((was-foreground t))
426     (loop
427      (with-session-lock (*session*)
428        (let ((int-t (session-interactive-threads *session*)))
429          (when (eq (car int-t) *current-thread*)
430            (unless was-foreground
431              (format *query-io* "Resuming thread ~A~%" *current-thread*))
432            (return-from get-foreground t))
433          (setf was-foreground nil)
434          (unless (member *current-thread* int-t)
435            (setf (cdr (last int-t))
436                  (list *current-thread*)))
437          (condition-wait
438           (session-interactive-threads-queue *session*)
439           (session-lock *session*)))))))
440
441 (defun release-foreground (&optional next)
442   #!+sb-doc
443   "Background this thread.  If NEXT is supplied, arrange for it to
444 have the foreground next."
445   #!-sb-thread (declare (ignore next))
446   #!-sb-thread nil
447   #!+sb-thread
448   (with-session-lock (*session*)
449     (when (rest (session-interactive-threads *session*))
450       (setf (session-interactive-threads *session*)
451             (delete *current-thread* (session-interactive-threads *session*))))
452     (when next
453       (setf (session-interactive-threads *session*)
454             (list* next
455                    (delete next (session-interactive-threads *session*)))))
456     (condition-broadcast (session-interactive-threads-queue *session*))))
457
458 (defun foreground-thread ()
459   (car (session-interactive-threads *session*)))
460
461 (defun make-listener-thread (tty-name)
462   (assert (probe-file tty-name))
463   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
464          (out (sb!unix:unix-dup in))
465          (err (sb!unix:unix-dup in)))
466     (labels ((thread-repl ()
467                (sb!unix::unix-setsid)
468                (let* ((sb!impl::*stdin*
469                        (make-fd-stream in :input t :buffering :line
470                                               :dual-channel-p t))
471                       (sb!impl::*stdout*
472                        (make-fd-stream out :output t :buffering :line
473                                               :dual-channel-p t))
474                       (sb!impl::*stderr*
475                        (make-fd-stream err :output t :buffering :line
476                                               :dual-channel-p t))
477                       (sb!impl::*tty*
478                        (make-fd-stream err :input t :output t
479                                               :buffering :line
480                                               :dual-channel-p t))
481                       (sb!impl::*descriptor-handlers* nil))
482                  (with-new-session ()
483                    (unwind-protect
484                         (sb!impl::toplevel-repl nil)
485                      (sb!int:flush-standard-output-streams))))))
486       (make-thread #'thread-repl))))
487
488 ;;;; the beef
489
490 (defun make-thread (function &key name)
491   #!+sb-doc
492   "Create a new thread of NAME that runs FUNCTION. When the function
493 returns the thread exits."
494   #!-sb-thread (declare (ignore function name))
495   #!-sb-thread (error "Not supported in unithread builds.")
496   #!+sb-thread
497   (let* ((thread (%make-thread :name name))
498          (setup-sem (make-semaphore :name "Thread setup semaphore"))
499          (real-function (coerce function 'function))
500          (initial-function
501           (lambda ()
502             ;; in time we'll move some of the binding presently done in C
503             ;; here too
504             (let ((*current-thread* thread)
505                   (sb!kernel::*restart-clusters* nil)
506                   (sb!kernel::*handler-clusters* nil)
507                   (sb!kernel::*condition-restarts* nil)
508                   (sb!impl::*descriptor-handlers* nil)) ; serve-event
509               (setf (thread-os-thread thread) (current-thread-sap-id))
510               (with-mutex (*all-threads-lock*)
511                 (push thread *all-threads*))
512               (with-session-lock (*session*)
513                 (push thread (session-threads *session*)))
514               (setf (thread-%alive-p thread) t)
515               (signal-semaphore setup-sem)
516               ;; can't use handling-end-of-the-world, because that flushes
517               ;; output streams, and we don't necessarily have any (or we
518               ;; could be sharing them)
519               (catch 'sb!impl::toplevel-catcher
520                 (catch 'sb!impl::%end-of-the-world
521                   (with-simple-restart
522                       (terminate-thread
523                        (format nil
524                                "~~@<Terminate this thread (~A)~~@:>"
525                                *current-thread*))
526                     (unwind-protect
527                          (progn
528                            ;; now that most things have a chance to
529                            ;; work properly without messing up other
530                            ;; threads, it's time to enable signals
531                            (sb!unix::reset-signal-mask)
532                            (funcall real-function))
533                       ;; we're going down, can't handle
534                       ;; interrupts sanely anymore
535                       (let ((sb!impl::*gc-inhibit* t))
536                         (block-blockable-signals)
537                         (setf (thread-%alive-p thread) nil)
538                         (setf (thread-os-thread thread) nil)
539                         ;; and remove what can be the last
540                         ;; reference to this thread
541                         (handle-thread-exit thread)))))))
542             (values))))
543     (with-pinned-objects (initial-function)
544       (let ((os-thread
545              ;; don't let the child inherit *CURRENT-THREAD* because that
546              ;; can prevent gc'ing this thread while the child runs
547              (let ((*current-thread* nil))
548                (%create-thread
549                 (sb!kernel:get-lisp-obj-address initial-function)))))
550         (when (zerop os-thread)
551           (error "Can't create a new thread"))
552         (wait-on-semaphore setup-sem)
553         thread))))
554
555 (defun destroy-thread (thread)
556   #!+sb-doc
557   "Deprecated. Same as TERMINATE-THREAD."
558   (terminate-thread thread))
559
560 (define-condition interrupt-thread-error (error)
561   ((thread :reader interrupt-thread-error-thread :initarg :thread))
562   #!+sb-doc
563   (:documentation "Interrupting thread failed.")
564   (:report (lambda (c s)
565              (format s "Interrupt thread failed: thread ~A has exited."
566                      (interrupt-thread-error-thread c)))))
567
568 #!+sb-doc
569 (setf (sb!kernel:fdocumentation 'interrupt-thread-error-thread 'function)
570       "The thread that was not interrupted.")
571
572 (defmacro with-interruptions-lock ((thread) &body body)
573   `(without-interrupts
574      (with-mutex ((thread-interruptions-lock ,thread))
575        ,@body)))
576
577 ;; Called from the signal handler.
578 (defun run-interruption ()
579   (in-interruption ()
580    (let ((interruption (with-interruptions-lock (*current-thread*)
581                          (pop (thread-interruptions *current-thread*)))))
582      (with-interrupts
583        (funcall interruption)))))
584
585 ;; The order of interrupt execution is peculiar. If thread A
586 ;; interrupts thread B with I1, I2 and B for some reason receives I1
587 ;; when FUN2 is already on the list, then it is FUN2 that gets to run
588 ;; first. But when FUN2 is run SIG_INTERRUPT_THREAD is enabled again
589 ;; and I2 hits pretty soon in FUN2 and run FUN1. This is of course
590 ;; just one scenario, and the order of thread interrupt execution is
591 ;; undefined.
592 (defun interrupt-thread (thread function)
593   #!+sb-doc
594   "Interrupt the live THREAD and make it run FUNCTION. A moderate
595 degree of care is expected for use of INTERRUPT-THREAD, due to its
596 nature: if you interrupt a thread that was holding important locks
597 then do something that turns out to need those locks, you probably
598 won't like the effect."
599   #!-sb-thread (declare (ignore thread))
600   ;; not quite perfect, because it does not take WITHOUT-INTERRUPTS
601   ;; into account
602   #!-sb-thread
603   (funcall function)
604   #!+sb-thread
605   (if (eq thread *current-thread*)
606       (funcall function)
607       (let ((os-thread (thread-os-thread thread)))
608         (cond ((not os-thread)
609                (error 'interrupt-thread-error :thread thread))
610               (t
611                (with-interruptions-lock (thread)
612                  (push function (thread-interruptions thread)))
613                (when (minusp (signal-interrupt-thread os-thread))
614                  (error 'interrupt-thread-error :thread thread)))))))
615
616 (defun terminate-thread (thread)
617   #!+sb-doc
618   "Terminate the thread identified by THREAD, by causing it to run
619 SB-EXT:QUIT - the usual cleanup forms will be evaluated"
620   (interrupt-thread thread 'sb!ext:quit))
621
622 ;;; internal use only.  If you think you need to use this, either you
623 ;;; are an SBCL developer, are doing something that you should discuss
624 ;;; with an SBCL developer first, or are doing something that you
625 ;;; should probably discuss with a professional psychiatrist first
626 #!+sb-thread
627 (defun thread-sap-for-id (id)
628   (let ((thread-sap (alien-sap (extern-alien "all_threads" (* t)))))
629     (loop
630      (when (sap= thread-sap (int-sap 0)) (return nil))
631      (let ((os-thread (sap-ref-word thread-sap
632                                     (* sb!vm:n-word-bytes
633                                        sb!vm::thread-os-thread-slot))))
634        (print os-thread)
635        (when (= os-thread id) (return thread-sap))
636        (setf thread-sap
637              (sap-ref-sap thread-sap (* sb!vm:n-word-bytes
638                                         sb!vm::thread-next-slot)))))))
639
640 #!+sb-thread
641 (defun symbol-value-in-thread (symbol thread-sap)
642   (let* ((index (sb!vm::symbol-tls-index symbol))
643          (tl-val (sap-ref-word thread-sap
644                                (* sb!vm:n-word-bytes index))))
645     (if (eql tl-val sb!vm::no-tls-value-marker-widetag)
646         (sb!vm::symbol-global-value symbol)
647         (sb!kernel:make-lisp-obj tl-val))))