0.8.2.5:
[sbcl.git] / src / code / target-thread.lisp
1 (in-package "SB!THREAD")
2
3 (sb!alien::define-alien-routine ("create_thread" %create-thread)
4      sb!alien:unsigned-long
5   (lisp-fun-address sb!alien:unsigned-long))
6
7 (defun make-thread (function)
8   (let ((real-function (coerce function 'function)))
9     (%create-thread
10      (sb!kernel:get-lisp-obj-address
11       (lambda ()
12         ;; in time we'll move some of the binding presently done in C
13         ;; here too
14         (let ((sb!kernel::*restart-clusters* nil)
15               (sb!impl::*descriptor-handlers* nil); serve-event
16               (sb!impl::*available-buffers* nil)) ;for fd-stream
17           ;; can't use handling-end-of-the-world, because that flushes
18           ;; output streams, and we don't necessarily have any (or we
19           ;; could be sharing them)
20           (sb!sys:enable-interrupt :sigint :ignore)
21           (sb!unix:unix-exit
22            (catch 'sb!impl::%end-of-the-world 
23              (with-simple-restart 
24                  (destroy-thread
25                   (format nil "~~@<Destroy this thread (~A)~~@:>"
26                           (current-thread-id)))
27                (funcall real-function))
28              0))))))))
29
30 (defun destroy-thread (thread-id)
31   (sb!unix:unix-kill thread-id :sigterm)
32   ;; may have been stopped for some reason, so now wake it up to
33   ;; deliver the TERM
34   (sb!unix:unix-kill thread-id :sigcont))
35
36 ;; Conventional wisdom says that it's a bad idea to use these unless
37 ;; you really need to.  Use a lock or a waitqueue instead
38 (defun suspend-thread (thread-id)
39   (sb!unix:unix-kill thread-id :sigstop))
40 (defun resume-thread (thread-id)
41   (sb!unix:unix-kill thread-id :sigcont))
42
43 (defun current-thread-id ()
44   (sb!sys:sap-int
45    (sb!vm::current-thread-offset-sap sb!vm::thread-pid-slot)))
46
47 ;;;; iterate over the in-memory threads
48
49 (defun mapcar-threads (function)
50   "Call FUNCTION once for each known thread, giving it the thread structure as argument"
51   (let ((function (coerce function 'function)))
52     (loop for thread = (alien-sap (extern-alien "all_threads" (* t)))
53           then  (sb!sys:sap-ref-sap thread (* 4 sb!vm::thread-next-slot))
54           until (sb!sys:sap= thread (sb!sys:int-sap 0))
55           collect (funcall function thread))))
56
57 ;;;; queues, locks 
58
59 ;; spinlocks use 0 as "free" value: higher-level locks use NIL
60 (defun get-spinlock (lock offset new-value)
61   (declare (optimize (speed 3) (safety 0)))
62   (loop until
63         (eql (sb!vm::%instance-set-conditional lock offset 0 new-value) 0)))
64
65 (defmacro with-spinlock ((queue) &body body)
66   (with-unique-names (pid)
67     `(unwind-protect
68       (let ((,pid (current-thread-id)))
69         (get-spinlock ,queue 2 ,pid)
70         ,@body)
71       (setf (waitqueue-lock ,queue) 0))))
72
73 ;;;; the higher-level locking operations are based on waitqueues
74
75 (defstruct waitqueue
76   (name nil :type (or null simple-base-string))
77   (lock 0)
78   (data nil))
79
80 (defstruct (mutex (:include waitqueue))
81   (value nil))
82
83 (sb!alien:define-alien-routine "block_sigcont"  void)
84 (sb!alien:define-alien-routine "unblock_sigcont_and_sleep"  void)
85
86 ;;; this should only be called while holding the queue spinlock.
87 ;;; it releases the spinlock before sleeping
88 (defun wait-on-queue (queue &optional lock)
89   (let ((pid (current-thread-id)))
90     ;; FIXME what should happen if we get interrupted when we've blocked
91     ;; the sigcont?  For that matter, can we get interrupted?
92     (block-sigcont)
93     (when lock (release-mutex lock))
94     (sb!sys:without-interrupts
95      (pushnew pid (waitqueue-data queue)))
96     (setf (waitqueue-lock queue) 0)
97     (unblock-sigcont-and-sleep)))
98
99 ;;; this should only be called while holding the queue spinlock.  It doesn't
100 ;;; release it
101 (defun dequeue (queue)
102   (let ((pid (current-thread-id)))
103     (sb!sys:without-interrupts     
104      (setf (waitqueue-data queue)
105            (delete pid (waitqueue-data queue))))))
106
107 ;;; this should probably only be called while holding the queue spinlock.
108 ;;; not sure
109 (defun signal-queue-head (queue)
110   (let ((p (car (waitqueue-data queue))))
111     (when p (sb!unix:unix-kill p  :sigcont))))
112
113 ;;;; mutex
114
115 (defun get-mutex (lock &optional new-value (wait-p t))
116   (declare (type mutex lock))
117   (let ((pid (current-thread-id)))
118     (unless new-value (setf new-value pid))
119     (assert (not (eql new-value (mutex-value lock))))
120     (get-spinlock lock 2 pid)
121     (loop
122      (unless
123          ;; args are object slot-num old-value new-value
124          (sb!vm::%instance-set-conditional lock 4 nil new-value)
125        (dequeue lock)
126        (setf (waitqueue-lock lock) 0)
127        (return t))
128      (unless wait-p
129        (setf (waitqueue-lock lock) 0)
130        (return nil))
131      (wait-on-queue lock nil))))
132
133 (defun release-mutex (lock &optional (new-value nil))
134   (declare (type mutex lock))
135   ;; we assume the lock is ours to release
136   (with-spinlock (lock)
137     (setf (mutex-value lock) new-value)
138     (signal-queue-head lock)))
139
140
141 (defmacro with-mutex ((mutex &key value (wait-p t))  &body body)
142   (with-unique-names (got)
143     `(let ((,got (get-mutex ,mutex ,value ,wait-p)))
144       (when ,got
145         (unwind-protect
146              (progn ,@body)
147           (release-mutex ,mutex))))))
148
149
150 ;;;; condition variables
151
152 (defun condition-wait (queue lock)
153   "Atomically release LOCK and enqueue ourselves on QUEUE.  Another
154 thread may subsequently notify us using CONDITION-NOTIFY, at which
155 time we reacquire LOCK and return to the caller."
156   (unwind-protect
157        (progn
158          (get-spinlock queue 2 (current-thread-id))
159          (wait-on-queue queue lock))
160     ;; If we are interrupted while waiting, we should do these things
161     ;; before returning.  Ideally, in the case of an unhandled signal,
162     ;; we should do them before entering the debugger, but this is
163     ;; better than nothing.
164     (with-spinlock (queue)
165       (dequeue queue))
166     (get-mutex lock)))
167
168 (defun condition-notify (queue)
169   "Notify one of the processes waiting on QUEUE"
170   (signal-queue-head queue))
171
172
173 ;;;; multiple independent listeners
174
175 (defvar *session-lock* nil)
176
177 (defun make-listener-thread (tty-name)  
178   (assert (probe-file tty-name))
179   ;; FIXME probably still need to do some tty stuff to get signals
180   ;; delivered correctly.
181   ;; FIXME 
182   (let* ((in (sb!unix:unix-open (namestring tty-name) sb!unix:o_rdwr #o666))
183          (out (sb!unix:unix-dup in))
184          (err (sb!unix:unix-dup in)))
185     (labels ((thread-repl () 
186                (sb!unix::unix-setsid)
187                (let* ((*session-lock*
188                        (make-mutex :name (format nil "lock for ~A" tty-name)))
189                       (sb!impl::*stdin* 
190                        (sb!sys:make-fd-stream in :input t :buffering :line))
191                       (sb!impl::*stdout* 
192                        (sb!sys:make-fd-stream out :output t :buffering :line))
193                       (sb!impl::*stderr* 
194                        (sb!sys:make-fd-stream err :output t :buffering :line))
195                       (sb!impl::*tty* 
196                        (sb!sys:make-fd-stream err :input t :output t :buffering :line))
197                       (sb!impl::*descriptor-handlers* nil))
198                  (get-mutex *session-lock*)
199                  (sb!sys:enable-interrupt :sigint #'sb!unix::sigint-handler)
200                  (unwind-protect
201                       (sb!impl::toplevel-repl nil)
202                    (sb!int:flush-standard-output-streams)))))
203       (make-thread #'thread-repl))))
204   
205 ;;;; job control
206
207 (defvar *background-threads-wait-for-debugger* t)
208 ;;; may be T, NIL, or a function called with a stream and thread id 
209 ;;; as its two arguments, returning NIl or T
210
211 ;;; called from top of invoke-debugger
212 (defun debugger-wait-until-foreground-thread (stream)
213   "Returns T if thread had been running in background, NIL if it was
214 already the foreground thread, or transfers control to the first applicable
215 restart if *BACKGROUND-THREADS-WAIT-FOR-DEBUGGER* says to do that instead"
216   (let* ((wait-p *background-threads-wait-for-debugger*)
217          (*background-threads-wait-for-debugger* nil)
218          (lock *session-lock*))
219     (when (not (eql (mutex-value lock)   (CURRENT-THREAD-ID)))
220       (when (functionp wait-p) 
221         (setf wait-p 
222               (funcall wait-p stream (CURRENT-THREAD-ID))))
223       (cond (wait-p (get-foreground))
224             (t  (invoke-restart (car (compute-restarts))))))))
225
226 ;;; install this with (setf SB!INT:*REPL-PROMPT-FUN* #'thread-prompt-fun)
227 ;;; One day it will be default
228 (defun thread-repl-prompt-fun (out-stream)
229   (let ((lock *session-lock*))
230     (get-foreground)
231     (let ((stopped-threads (waitqueue-data lock)))
232       (when stopped-threads
233         (format out-stream "~{~&Thread ~A suspended~}~%" stopped-threads))
234       (sb!impl::repl-prompt-fun out-stream))))
235
236 (defun resume-stopped-thread (id)
237   (let ((pid (current-thread-id))
238         (lock *session-lock*)) 
239     (with-spinlock (lock)
240       (setf (waitqueue-data lock)
241             (cons id (delete id  (waitqueue-data lock)))))
242     (release-foreground)))
243
244 (defstruct rwlock
245   (name nil :type (or null simple-base-string))
246   (value 0 :type fixnum)
247   (max-readers nil :type (or fixnum null))
248   (max-writers 1 :type fixnum))
249 #+nil
250 (macrolet
251     ((make-rwlocking-function (lock-fn unlock-fn increment limit test)
252        (let ((do-update '(when (eql old-value
253                                 (sb!vm::%instance-set-conditional
254                                  lock 2 old-value new-value))
255                           (return (values t old-value))))
256              (vars `((timeout (and timeout (+ (get-internal-real-time) timeout)))
257                      old-value
258                      new-value
259                      (limit ,limit))))
260          (labels ((do-setfs (v) `(setf old-value (rwlock-value lock)
261                                   new-value (,v old-value ,increment))))
262            `(progn
263              (defun ,lock-fn (lock timeout)
264                (declare (type rwlock lock))
265                (let ,vars
266                  (loop
267                   ,(do-setfs '+)
268                   (when ,test
269                     ,do-update)
270                   (when (sleep-a-bit timeout) (return nil)) ;expired
271                   )))
272              ;; unlock doesn't need timeout or test-in-range
273              (defun ,unlock-fn (lock)
274                (declare (type rwlock lock))
275                (declare (ignorable limit))
276                (let ,(cdr vars)
277                  (loop
278                   ,(do-setfs '-)
279                   ,do-update))))))))
280     
281   (make-rwlocking-function %lock-for-reading %unlock-for-reading 1
282                            (rwlock-max-readers lock)
283                            (and (>= old-value 0)
284                                 (or (null limit) (<= new-value limit))))
285   (make-rwlocking-function %lock-for-writing %unlock-for-writing -1
286                            (- (rwlock-max-writers lock))
287                            (and (<= old-value 0)
288                                 (>= new-value limit))))
289 #+nil  
290 (defun get-rwlock (lock direction &optional timeout)
291   (ecase direction
292     (:read (%lock-for-reading lock timeout))
293     (:write (%lock-for-writing lock timeout))))
294 #+nil
295 (defun free-rwlock (lock direction)
296   (ecase direction
297     (:read (%unlock-for-reading lock))
298     (:write (%unlock-for-writing lock))))
299
300 ;;;; beyond this point all is commented.
301
302 ;;; Lock-Wait-With-Timeout  --  Internal
303 ;;;
304 ;;; Wait with a timeout for the lock to be free and acquire it for the
305 ;;; *current-process*.
306 ;;;
307 #+nil
308 (defun lock-wait-with-timeout (lock whostate timeout)
309   (declare (type lock lock))
310   (process-wait-with-timeout
311    whostate timeout
312    #'(lambda ()
313        (declare (optimize (speed 3)))
314        #-i486
315        (unless (lock-process lock)
316          (setf (lock-process lock) *current-process*))
317        #+i486
318        (null (kernel:%instance-set-conditional
319               lock 2 nil *current-process*)))))
320
321 ;;; With-Lock-Held  --  Public
322 ;;;
323 #+nil
324 (defmacro with-lock-held ((lock &optional (whostate "Lock Wait")
325                                 &key (wait t) timeout)
326                           &body body)
327   "Execute the body with the lock held. If the lock is held by another
328   process then the current process waits until the lock is released or
329   an optional timeout is reached. The optional wait timeout is a time in
330   seconds acceptable to process-wait-with-timeout.  The results of the
331   body are return upon success and NIL is return if the timeout is
332   reached. When the wait key is NIL and the lock is held by another
333   process then NIL is return immediately without processing the body."
334   (let ((have-lock (gensym)))
335     `(let ((,have-lock (eq (lock-process ,lock) *current-process*)))
336       (unwind-protect
337            ,(cond ((and timeout wait)
338                    `(progn
339                       (when (and (error-check-lock-p ,lock) ,have-lock)
340                         (error "Dead lock"))
341                       (when (or ,have-lock
342                                  #+i486 (null (kernel:%instance-set-conditional
343                                                ,lock 2 nil *current-process*))
344                                  #-i486 (seize-lock ,lock)
345                                  (if ,timeout
346                                      (lock-wait-with-timeout
347                                       ,lock ,whostate ,timeout)
348                                      (lock-wait ,lock ,whostate)))
349                         ,@body)))
350                   (wait
351                    `(progn
352                       (when (and (error-check-lock-p ,lock) ,have-lock)
353                         (error "Dead lock"))
354                       (unless (or ,have-lock
355                                  #+i486 (null (kernel:%instance-set-conditional
356                                                ,lock 2 nil *current-process*))
357                                  #-i486 (seize-lock ,lock))
358                         (lock-wait ,lock ,whostate))
359                       ,@body))
360                   (t
361                    `(when (or (and (recursive-lock-p ,lock) ,have-lock)
362                               #+i486 (null (kernel:%instance-set-conditional
363                                             ,lock 2 nil *current-process*))
364                               #-i486 (seize-lock ,lock))
365                       ,@body)))
366         (unless ,have-lock
367           #+i486 (kernel:%instance-set-conditional
368                   ,lock 2 *current-process* nil)
369           #-i486 (when (eq (lock-process ,lock) *current-process*)
370                    (setf (lock-process ,lock) nil)))))))
371
372
373