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