0.9.1.59:
[sbcl.git] / tests / threads.impure.lisp
1 ;;;; miscellaneous tests of thread stuff
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5 ;;;;
6 ;;;; While most of SBCL is derived from the CMU CL system, the test
7 ;;;; files (like this one) were written from scratch after the fork
8 ;;;; from CMU CL.
9 ;;; 
10 ;;;; This software is in the public domain and is provided with
11 ;;;; absoluely no warranty. See the COPYING and CREDITS files for
12 ;;;; more information.
13
14 #-sb-thread (quit :unix-status 104)
15
16 (in-package "SB-THREAD") ; this is white-box testing, really
17
18 ;;; We had appalling scaling properties for a while.  Make sure they
19 ;;; don't reappear.
20 (defun scaling-test (function &optional (nthreads 5))
21   "Execute FUNCTION with NTHREADS lurking to slow it down."
22   (let ((queue (sb-thread:make-waitqueue))
23         (mutex (sb-thread:make-mutex)))
24     ;; Start NTHREADS idle threads.
25     (dotimes (i nthreads)
26       (sb-thread:make-thread (lambda ()
27                                (sb-thread:condition-wait queue mutex)
28                                (sb-ext:quit))))
29     (let ((start-time (get-internal-run-time)))
30       (funcall function)
31       (prog1 (- (get-internal-run-time) start-time)
32         (sb-thread:condition-broadcast queue)))))
33 (defun fact (n)
34   "A function that does work with the CPU."
35   (if (zerop n) 1 (* n (fact (1- n)))))
36 (let ((work (lambda () (fact 15000))))
37   (let ((zero (scaling-test work 0))
38         (four (scaling-test work 4)))
39     ;; a slightly weak assertion, but good enough for starters.
40     (assert (< four (* 1.5 zero)))))
41
42 ;;; For one of the interupt-thread tests, we want a foreign function
43 ;;; that does not make syscalls
44
45 (with-open-file (o "threads-foreign.c" :direction :output :if-exists :supersede)
46   (format o "void loop_forever() { while(1) ; }~%"))
47 (sb-ext:run-program     
48  "cc"
49  (or #+linux '("-shared" "-o" "threads-foreign.so" "threads-foreign.c")
50      (error "Missing shared library compilation options for this platform"))
51  :search t)
52 (sb-alien:load-shared-object "threads-foreign.so")
53 (sb-alien:define-alien-routine loop-forever sb-alien:void)
54
55
56 ;;; elementary "can we get a lock and release it again"
57 (let ((l (make-mutex :name "foo"))
58       (p (current-thread-id)))
59   (assert (eql (mutex-value l) nil) nil "1")
60   (assert (eql (mutex-lock l) 0) nil "2")
61   (sb-thread:get-mutex l)
62   (assert (eql (mutex-value l) p) nil "3")
63   (assert (eql (mutex-lock l) 0) nil "4")
64   (sb-thread:release-mutex l)
65   (assert (eql (mutex-value l) nil) nil "5")
66   (assert (eql (mutex-lock l) 0)  nil "6")
67   (describe l))
68
69 ;; test that SLEEP actually sleeps for at least the given time, even
70 ;; if interrupted by another thread exiting/a gc/anything
71 (let ((start-time (get-universal-time)))
72   (make-thread (lambda () (sleep 1))) ; kid waits 1 then dies ->SIG_THREAD_EXIT
73   (sleep 5)
74   (assert (>= (get-universal-time) (+ 5 start-time))))
75
76
77 (let ((queue (make-waitqueue :name "queue"))
78       (lock (make-mutex :name "lock")))
79   (labels ((in-new-thread ()
80              (with-mutex (lock)
81                (assert (eql (mutex-value lock) (current-thread-id)))
82                (format t "~A got mutex~%" (current-thread-id))
83                ;; now drop it and sleep
84                (condition-wait queue lock)
85                ;; after waking we should have the lock again
86                (assert (eql (mutex-value lock) (current-thread-id))))))
87     (make-thread #'in-new-thread)
88     (sleep 2)                           ; give it  a chance to start
89     ;; check the lock is free while it's asleep
90     (format t "parent thread ~A~%" (current-thread-id))
91     (assert (eql (mutex-value lock) nil))    
92     (assert (eql (mutex-lock lock) 0))
93     (with-mutex (lock)
94       (condition-notify queue))
95     (sleep 1)))
96
97 (let ((queue (make-waitqueue :name "queue"))
98       (lock (make-mutex :name "lock")))
99   (labels ((ours-p (value)
100              (sb-vm:control-stack-pointer-valid-p
101               (sb-sys:int-sap (sb-kernel:get-lisp-obj-address value))))
102            (in-new-thread ()
103              (with-recursive-lock (lock)
104                (assert (ours-p (mutex-value lock)))
105                (format t "~A got mutex~%" (mutex-value lock))
106                ;; now drop it and sleep
107                (condition-wait queue lock)
108                ;; after waking we should have the lock again
109                (format t "woken, ~A got mutex~%" (mutex-value lock))
110                (assert (ours-p (mutex-value lock))))))
111     (make-thread #'in-new-thread)
112     (sleep 2)                           ; give it  a chance to start
113     ;; check the lock is free while it's asleep
114     (format t "parent thread ~A~%" (current-thread-id))
115     (assert (eql (mutex-value lock) nil))    
116     (assert (eql (mutex-lock lock) 0))
117     (with-recursive-lock (lock)
118       (condition-notify queue))
119     (sleep 1)))
120
121 (let ((mutex (make-mutex :name "contended")))
122   (labels ((run ()
123              (let ((me (current-thread-id)))
124                (dotimes (i 100)
125                  (with-mutex (mutex)
126                    (sleep .1)
127                    (assert (eql (mutex-value mutex) me)))
128                  (assert (not (eql (mutex-value mutex) me))))
129                (format t "done ~A~%" (current-thread-id)))))
130     (let ((kid1 (make-thread #'run))
131           (kid2 (make-thread #'run)))
132       (format t "contention ~A ~A~%" kid1 kid2))))
133
134 (defun test-interrupt (function-to-interrupt &optional quit-p)
135   (let ((child  (make-thread function-to-interrupt)))
136     ;;(format t "gdb ./src/runtime/sbcl ~A~%attach ~A~%" child child)
137     (sleep 2)
138     (format t "interrupting child ~A~%" child)
139     (interrupt-thread child
140                       (lambda ()
141                         (format t "child pid ~A~%" (current-thread-id))
142                         (when quit-p (sb-ext:quit))))
143     (sleep 1)
144     child))
145
146 ;;; separate tests for (a) interrupting Lisp code, (b) C code, (c) a syscall,
147 ;;; (d) waiting on a lock, (e) some code which we hope is likely to be
148 ;;; in pseudo-atomic
149
150 (let ((child (test-interrupt (lambda () (loop)))))  (terminate-thread child))
151
152 (test-interrupt #'loop-forever :quit)
153
154 (let ((child (test-interrupt (lambda () (loop (sleep 2000))))))
155   (terminate-thread child))
156                 
157 (let ((lock (make-mutex :name "loctite"))
158       child)
159   (with-mutex (lock)
160     (setf child (test-interrupt
161                  (lambda ()
162                    (with-mutex (lock)
163                      (assert (eql (mutex-value lock) (current-thread-id))))
164                    (assert (not (eql (mutex-value lock) (current-thread-id))))
165                    (sleep 60))))
166     ;;hold onto lock for long enough that child can't get it immediately
167     (sleep 20)
168     (interrupt-thread child (lambda () (format t "l ~A~%" (mutex-value lock))))
169     (format t "parent releasing lock~%"))
170   (terminate-thread child))
171
172 (defun alloc-stuff () (copy-list '(1 2 3 4 5)))
173
174 (let ((c (test-interrupt (lambda () (loop (alloc-stuff))))))
175   ;; NB this only works on x86: other ports don't have a symbol for
176   ;; pseudo-atomic atomicity
177   (format t "new thread ~A~%" c)
178   (dotimes (i 100)
179     (sleep (random 1d0))
180     (interrupt-thread c
181                       (lambda ()
182                         (princ ".") (force-output)
183                         (assert (zerop SB-KERNEL:*PSEUDO-ATOMIC-ATOMIC*)))))
184   (terminate-thread c))
185 (terpri)
186
187 (defparameter *interrupt-count* 0)
188
189 (declaim (notinline check-interrupt-count))
190 (defun check-interrupt-count (i)
191   (declare (optimize (debug 1) (speed 1)))
192   ;; This used to lose if eflags were not restored after an interrupt.
193   (unless (typep i 'fixnum)
194     (error "!!!!!!!!!!!")))
195
196 (let ((c (make-thread
197           (lambda ()
198             (handler-bind ((error #'(lambda (cond)
199                                       (princ cond)
200                                       (sb-debug:backtrace
201                                        most-positive-fixnum))))
202               (loop (check-interrupt-count *interrupt-count*)))))))
203   (let ((func (lambda ()
204                 (princ ".")
205                 (force-output)
206                 (sb-impl::atomic-incf/symbol *interrupt-count*))))
207     (sb-sys:with-pinned-objects (func)
208       (setq *interrupt-count* 0)
209       (dotimes (i 100)
210         (sleep (random 1d0))
211         (interrupt-thread c func))
212       (sleep 1)
213       (assert (= 100 *interrupt-count*))
214       (terminate-thread c))))
215
216 (format t "~&interrupt test done~%")
217
218 (let (a-done b-done)
219   (make-thread (lambda ()
220                  (dotimes (i 100) 
221                    (sb-ext:gc) (princ "\\") (force-output) )
222                  (setf a-done t)))
223   (make-thread (lambda ()
224                  (dotimes (i 25) 
225                    (sb-ext:gc :full t)
226                    (princ "/") (force-output))
227                  (setf b-done t)))
228   (loop
229    (when (and a-done b-done) (return))
230    (sleep 1)))
231
232 (terpri)
233
234 (defun waste (&optional (n 100000))
235   (loop repeat n do (make-string 16384)))
236
237 (loop for i below 100 do
238       (princ "!")
239       (force-output)
240       (sb-thread:make-thread
241        #'(lambda ()
242            (waste)))
243       (waste)
244       (sb-ext:gc))
245
246 (terpri)
247
248 (defparameter *aaa* nil)
249 (loop for i below 100 do
250       (princ "!")
251       (force-output)
252       (sb-thread:make-thread
253        #'(lambda ()
254            (let ((*aaa* (waste)))
255              (waste))))
256       (let ((*aaa* (waste)))
257         (waste))
258       (sb-ext:gc))
259
260 (format t "~&gc test done~%")
261
262 ;; this used to deadlock on session-lock
263 (sb-thread:make-thread (lambda () (sb-ext:gc)))
264 ;; expose thread creation races by exiting quickly
265 (sb-thread:make-thread (lambda ()))
266
267 (defun exercise-syscall (fn reference-errno)
268   (sb-thread:make-thread
269    (lambda ()
270      (loop do
271           (funcall fn)
272           (let ((errno (sb-unix::get-errno)))
273             (sleep (random 1.0))
274             (unless (eql errno reference-errno)
275               (format t "Got errno: ~A (~A) instead of ~A~%"
276                       errno
277                       (sb-unix::strerror)
278                       reference-errno)
279               (force-output)
280               (sb-ext:quit :unix-status 1)))))))
281
282 (let* ((nanosleep-errno (progn
283                           (sb-unix:nanosleep -1 0)
284                           (sb-unix::get-errno)))
285        (open-errno (progn
286                      (open "no-such-file"
287                            :if-does-not-exist nil)
288                      (sb-unix::get-errno)))
289        (threads
290         (list
291          (exercise-syscall (lambda () (sb-unix:nanosleep -1 0)) nanosleep-errno)
292          (exercise-syscall (lambda () (open "no-such-file"
293                                             :if-does-not-exist nil))
294                            open-errno)
295          (sb-thread:make-thread (lambda () (loop (sb-ext:gc) (sleep 1)))))))
296   (sleep 10)
297   (princ "terminating threads")
298   (dolist (thread threads)
299     (sb-thread:terminate-thread thread)))
300
301 (format t "~&errno test done~%")
302
303 (loop repeat 100 do
304       (let ((thread (sb-thread:make-thread (lambda () (sleep 0.1)))))
305         (sb-thread:interrupt-thread
306          thread
307          (lambda ()
308            (assert (find-restart 'sb-thread:terminate-thread))))))
309
310 (sb-ext:gc :full t)
311
312 (format t "~&thread startup sigmask test done~%")
313
314 #|  ;; a cll post from eric marsden
315 | (defun crash ()
316 |   (setq *debugger-hook*
317 |         (lambda (condition old-debugger-hook)
318 |           (debug:backtrace 10)
319 |           (unix:unix-exit 2)))
320 |   #+live-dangerously
321 |   (mp::start-sigalrm-yield)
322 |   (flet ((roomy () (loop (with-output-to-string (*standard-output*) (room)))))
323 |     (mp:make-process #'roomy)
324 |     (mp:make-process #'roomy)))
325 |#
326
327 ;; give the other thread time to die before we leave, otherwise the
328 ;; overall exit status is 0, not 104
329 (sleep 2) 
330
331 (sb-ext:quit :unix-status 104)