More unboxed-byte-addresses-are-word-addresses damage.
[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 ; WHITE-BOX TESTS
15
16 (in-package "SB-THREAD")
17 (use-package :test-util)
18 (use-package "ASSERTOID")
19
20 (setf sb-unix::*on-dangerous-wait* :error)
21
22 (defun wait-for-threads (threads)
23   (mapc (lambda (thread) (sb-thread:join-thread thread :default nil)) threads)
24   (assert (not (some #'sb-thread:thread-alive-p threads))))
25
26 (with-test (:name (:threads :trivia))
27   (assert (eql 1 (length (list-all-threads))))
28
29   (assert (eq *current-thread*
30               (find (thread-name *current-thread*) (list-all-threads)
31                     :key #'thread-name :test #'equal)))
32
33   (assert (thread-alive-p *current-thread*)))
34
35 (with-test (:name (:with-mutex :basics))
36   (let ((mutex (make-mutex)))
37     (with-mutex (mutex)
38       mutex)))
39
40 (with-test (:name (:with-spinlock :basics))
41   (let ((spinlock (make-spinlock)))
42     (with-spinlock (spinlock))))
43
44 (sb-alien:define-alien-routine "check_deferrables_blocked_or_lose"
45     void
46   (where sb-alien:unsigned-long))
47 (sb-alien:define-alien-routine "check_deferrables_unblocked_or_lose"
48     void
49   (where sb-alien:unsigned-long))
50
51 (with-test (:name (:interrupt-thread :basics :no-unwinding))
52   (let ((a 0))
53     (interrupt-thread *current-thread* (lambda () (setq a 1)))
54     (assert (eql a 1))))
55
56 (with-test (:name (:interrupt-thread :deferrables-blocked))
57   (sb-thread:interrupt-thread sb-thread:*current-thread*
58                               (lambda ()
59                                 (check-deferrables-blocked-or-lose 0))))
60
61 (with-test (:name (:interrupt-thread :deferrables-unblocked))
62   (sb-thread:interrupt-thread sb-thread:*current-thread*
63                               (lambda ()
64                                 (with-interrupts
65                                   (check-deferrables-unblocked-or-lose 0)))))
66
67 (with-test (:name (:interrupt-thread :nlx))
68   (catch 'xxx
69     (sb-thread:interrupt-thread sb-thread:*current-thread*
70                                 (lambda ()
71                                   (check-deferrables-blocked-or-lose 0)
72                                   (throw 'xxx nil))))
73   (check-deferrables-unblocked-or-lose 0))
74
75 #-sb-thread (sb-ext:quit :unix-status 104)
76
77 ;;;; Now the real tests...
78
79 (with-test (:name (:interrupt-thread :deferrables-unblocked-by-spinlock))
80   (let ((spinlock (sb-thread::make-spinlock))
81         (thread (sb-thread:make-thread (lambda ()
82                                          (loop (sleep 1))))))
83     (sb-thread::get-spinlock spinlock)
84     (sb-thread:interrupt-thread thread
85                                 (lambda ()
86                                   (check-deferrables-blocked-or-lose 0)
87                                   (sb-thread::get-spinlock spinlock)
88                                   (check-deferrables-unblocked-or-lose 0)
89                                   (sb-ext:quit)))
90     (sleep 1)
91     (sb-thread::release-spinlock spinlock)))
92
93 ;;; compare-and-swap
94
95 (defmacro defincf (name accessor &rest args)
96   `(defun ,name (x)
97      (let* ((old (,accessor x ,@args))
98          (new (1+ old)))
99     (loop until (eq old (sb-ext:compare-and-swap (,accessor x ,@args) old new))
100        do (setf old (,accessor x ,@args)
101                 new (1+ old)))
102     new)))
103
104 (defstruct cas-struct (slot 0))
105
106 (defincf incf-car car)
107 (defincf incf-cdr cdr)
108 (defincf incf-slot cas-struct-slot)
109 (defincf incf-symbol-value symbol-value)
110 (defincf incf-svref/1 svref 1)
111 (defincf incf-svref/0 svref 0)
112
113 (defmacro def-test-cas (name init incf op)
114   `(with-test (:name ,name)
115      (flet ((,name (n)
116               (declare (fixnum n))
117               (let* ((x ,init)
118                      (run nil)
119                      (threads
120                       (loop repeat 10
121                             collect (sb-thread:make-thread
122                                      (lambda ()
123                                        (loop until run
124                                              do (sb-thread:thread-yield))
125                                        (loop repeat n do (,incf x)))))))
126                 (setf run t)
127                 (dolist (th threads)
128                   (sb-thread:join-thread th))
129                 (assert (= (,op x) (* 10 n))))))
130        (,name 200000))))
131
132 (def-test-cas test-cas-car (cons 0 nil) incf-car car)
133 (def-test-cas test-cas-cdr (cons nil 0) incf-cdr cdr)
134 (def-test-cas test-cas-slot (make-cas-struct) incf-slot cas-struct-slot)
135 (def-test-cas test-cas-value (let ((x '.x.))
136                                (set x 0)
137                                x)
138   incf-symbol-value symbol-value)
139 (def-test-cas test-cas-svref/0 (vector 0 nil) incf-svref/0 (lambda (x)
140                                                              (svref x 0)))
141 (def-test-cas test-cas-svref/1 (vector nil 0) incf-svref/1 (lambda (x)
142                                                              (svref x 1)))
143 (format t "~&compare-and-swap tests done~%")
144
145 (with-test (:name (:threads :more-trivia)))
146 (let ((old-threads (list-all-threads))
147       (thread (make-thread (lambda ()
148                              (assert (find *current-thread* *all-threads*))
149                              (sleep 2))))
150       (new-threads (list-all-threads)))
151   (assert (thread-alive-p thread))
152   (assert (eq thread (first new-threads)))
153   (assert (= (1+ (length old-threads)) (length new-threads)))
154   (sleep 3)
155   (assert (not (thread-alive-p thread))))
156
157 (with-test (:name (:join-thread :nlx :default))
158   (let ((sym (gensym)))
159     (assert (eq sym (join-thread (make-thread (lambda () (sb-ext:quit)))
160                                  :default sym)))))
161
162 (with-test (:name (:join-thread :nlx :error))
163   (raises-error? (join-thread (make-thread (lambda () (sb-ext:quit))))
164                  join-thread-error))
165
166 (with-test (:name (:join-thread :multiple-values))
167   (assert (equal '(1 2 3)
168                  (multiple-value-list
169                   (join-thread (make-thread (lambda () (values 1 2 3))))))))
170
171 ;;; We had appalling scaling properties for a while.  Make sure they
172 ;;; don't reappear.
173 (defun scaling-test (function &optional (nthreads 5))
174   "Execute FUNCTION with NTHREADS lurking to slow it down."
175   (let ((queue (sb-thread:make-waitqueue))
176         (mutex (sb-thread:make-mutex)))
177     ;; Start NTHREADS idle threads.
178     (dotimes (i nthreads)
179       (sb-thread:make-thread (lambda ()
180                                (with-mutex (mutex)
181                                  (sb-thread:condition-wait queue mutex))
182                                (sb-ext:quit))))
183     (let ((start-time (get-internal-run-time)))
184       (funcall function)
185       (prog1 (- (get-internal-run-time) start-time)
186         (sb-thread:condition-broadcast queue)))))
187 (defun fact (n)
188   "A function that does work with the CPU."
189   (if (zerop n) 1 (* n (fact (1- n)))))
190 (let ((work (lambda () (fact 15000))))
191   (let ((zero (scaling-test work 0))
192         (four (scaling-test work 4)))
193     ;; a slightly weak assertion, but good enough for starters.
194     (assert (< four (* 1.5 zero)))))
195
196 ;;; For one of the interupt-thread tests, we want a foreign function
197 ;;; that does not make syscalls
198
199 (with-open-file (o "threads-foreign.c" :direction :output :if-exists :supersede)
200   (format o "void loop_forever() { while(1) ; }~%"))
201 (sb-ext:run-program "/bin/sh"
202                     '("run-compiler.sh" "-sbcl-pic" "-sbcl-shared"
203                       "-o" "threads-foreign.so" "threads-foreign.c")
204                     :environment (test-util::test-env))
205 (sb-alien:load-shared-object (truename "threads-foreign.so"))
206 (sb-alien:define-alien-routine loop-forever sb-alien:void)
207 (delete-file "threads-foreign.c")
208
209
210 ;;; elementary "can we get a lock and release it again"
211 (with-test (:name (:mutex :basics))
212   (let ((l (make-mutex :name "foo"))
213         (p *current-thread*))
214     (assert (eql (mutex-value l) nil) nil "1")
215     (sb-thread:get-mutex l)
216     (assert (eql (mutex-value l) p) nil "3")
217     (sb-thread:release-mutex l)
218     (assert (eql (mutex-value l) nil) nil "5")))
219
220 (with-test (:name (:with-recursive-lock :basics))
221   (labels ((ours-p (value)
222              (eq *current-thread* value)))
223     (let ((l (make-mutex :name "rec")))
224       (assert (eql (mutex-value l) nil) nil "1")
225       (sb-thread:with-recursive-lock (l)
226         (assert (ours-p (mutex-value l)) nil "3")
227         (sb-thread:with-recursive-lock (l)
228           (assert (ours-p (mutex-value l)) nil "4"))
229         (assert (ours-p (mutex-value l)) nil "5"))
230       (assert (eql (mutex-value l) nil) nil "6"))))
231
232 (with-test (:name (:with-recursive-spinlock :basics))
233   (labels ((ours-p (value)
234              (eq *current-thread* value)))
235     (let ((l (make-spinlock :name "rec")))
236       (assert (eql (spinlock-value l) nil) nil "1")
237       (with-recursive-spinlock (l)
238         (assert (ours-p (spinlock-value l)) nil "3")
239         (with-recursive-spinlock (l)
240           (assert (ours-p (spinlock-value l)) nil "4"))
241         (assert (ours-p (spinlock-value l)) nil "5"))
242       (assert (eql (spinlock-value l) nil) nil "6"))))
243
244 (with-test (:name (:mutex :nesting-mutex-and-recursive-lock))
245   (let ((l (make-mutex :name "a mutex")))
246     (with-mutex (l)
247       (with-recursive-lock (l)))))
248
249 (with-test (:name (:spinlock :nesting-spinlock-and-recursive-spinlock))
250   (let ((l (make-spinlock :name "a spinlock")))
251     (with-spinlock (l)
252       (with-recursive-spinlock (l)))))
253
254 (with-test (:name (:spinlock :more-basics))
255   (let ((l (make-spinlock :name "spinlock")))
256     (assert (eql (spinlock-value l) nil) ((spinlock-value l))
257             "spinlock not free (1)")
258     (with-spinlock (l)
259       (assert (eql (spinlock-value l) *current-thread*) ((spinlock-value l))
260               "spinlock not taken"))
261     (assert (eql (spinlock-value l) nil) ((spinlock-value l))
262             "spinlock not free (2)")))
263
264 ;; test that SLEEP actually sleeps for at least the given time, even
265 ;; if interrupted by another thread exiting/a gc/anything
266 (with-test (:name (:sleep :continue-sleeping-after-interrupt))
267   (let ((start-time (get-universal-time)))
268     (make-thread (lambda () (sleep 1) (sb-ext:gc :full t)))
269     (sleep 5)
270     (assert (>= (get-universal-time) (+ 5 start-time)))))
271
272
273 (with-test (:name (:condition-wait :basics-1))
274   (let ((queue (make-waitqueue :name "queue"))
275         (lock (make-mutex :name "lock"))
276         (n 0))
277     (labels ((in-new-thread ()
278                (with-mutex (lock)
279                  (assert (eql (mutex-value lock) *current-thread*))
280                  (format t "~A got mutex~%" *current-thread*)
281                  ;; now drop it and sleep
282                  (condition-wait queue lock)
283                  ;; after waking we should have the lock again
284                  (assert (eql (mutex-value lock) *current-thread*))
285                  (assert (eql n 1))
286                  (decf n))))
287       (make-thread #'in-new-thread)
288       (sleep 2)            ; give it  a chance to start
289       ;; check the lock is free while it's asleep
290       (format t "parent thread ~A~%" *current-thread*)
291       (assert (eql (mutex-value lock) nil))
292       (with-mutex (lock)
293         (incf n)
294         (condition-notify queue))
295       (sleep 1))))
296
297 (with-test (:name (:condition-wait :basics-2))
298   (let ((queue (make-waitqueue :name "queue"))
299         (lock (make-mutex :name "lock")))
300     (labels ((ours-p (value)
301                (eq *current-thread* value))
302              (in-new-thread ()
303                (with-recursive-lock (lock)
304                  (assert (ours-p (mutex-value lock)))
305                  (format t "~A got mutex~%" (mutex-value lock))
306                  ;; now drop it and sleep
307                  (condition-wait queue lock)
308                  ;; after waking we should have the lock again
309                  (format t "woken, ~A got mutex~%" (mutex-value lock))
310                  (assert (ours-p (mutex-value lock))))))
311       (make-thread #'in-new-thread)
312       (sleep 2)            ; give it  a chance to start
313       ;; check the lock is free while it's asleep
314       (format t "parent thread ~A~%" *current-thread*)
315       (assert (eql (mutex-value lock) nil))
316       (with-recursive-lock (lock)
317         (condition-notify queue))
318       (sleep 1))))
319
320 (with-test (:name (:mutex :contention))
321   (let ((mutex (make-mutex :name "contended")))
322     (labels ((run ()
323                (let ((me *current-thread*))
324                  (dotimes (i 100)
325                    (with-mutex (mutex)
326                      (sleep .03)
327                      (assert (eql (mutex-value mutex) me)))
328                    (assert (not (eql (mutex-value mutex) me))))
329                  (format t "done ~A~%" *current-thread*))))
330       (let ((kid1 (make-thread #'run))
331             (kid2 (make-thread #'run)))
332         (format t "contention ~A ~A~%" kid1 kid2)
333         (wait-for-threads (list kid1 kid2))))))
334
335 ;;; GRAB-MUTEX
336
337 (with-test (:name (:grab-mutex :waitp nil))
338   (let ((m (make-mutex)))
339     (with-mutex (m)
340       (assert (null (join-thread (make-thread
341                                   #'(lambda ()
342                                       (grab-mutex m :waitp nil)))))))))
343
344 (with-test (:name (:grab-mutex :timeout :acquisition-fail))
345   #+sb-lutex
346   (error "Mutex timeout not supported here.")
347   (let ((m (make-mutex))
348         (w (make-semaphore)))
349     (with-mutex (m)
350       (let ((th (make-thread
351                  #'(lambda ()
352                      (prog1
353                          (grab-mutex m :timeout 0.1)
354                        (signal-semaphore w))))))
355         ;; Wait for it to -- otherwise the detect the deadlock chain
356         ;; from JOIN-THREAD.
357         (wait-on-semaphore w)
358         (assert (null (join-thread th)))))))
359
360 (with-test (:name (:grab-mutex :timeout :acquisition-success))
361   #+sb-lutex
362   (error "Mutex timeout not supported here.")
363   (let ((m (make-mutex))
364         (child))
365     (with-mutex (m)
366       (setq child (make-thread #'(lambda () (grab-mutex m :timeout 1.0))))
367       (sleep 0.2))
368     (assert (eq (join-thread child) 't))))
369
370 (with-test (:name (:grab-mutex :timeout+deadline))
371   #+sb-lutex
372   (error "Mutex timeout not supported here.")
373   (let ((m (make-mutex))
374         (w (make-semaphore)))
375     (with-mutex (m)
376       (let ((th (make-thread #'(lambda ()
377                                  (sb-sys:with-deadline (:seconds 0.0)
378                                    (handler-case
379                                        (grab-mutex m :timeout 0.0)
380                                      (sb-sys:deadline-timeout ()
381                                        (signal-semaphore w)
382                                        :deadline)))))))
383         (wait-on-semaphore w)
384         (assert (eq (join-thread th) :deadline))))))
385
386 (with-test (:name (:grab-mutex :waitp+deadline))
387   #+sb-lutex
388   (error "Mutex timeout not supported here.")
389   (let ((m (make-mutex)))
390     (with-mutex (m)
391       (assert (eq (join-thread
392                    (make-thread #'(lambda ()
393                                     (sb-sys:with-deadline (:seconds 0.0)
394                                       (handler-case
395                                           (grab-mutex m :waitp nil)
396                                         (sb-sys:deadline-timeout ()
397                                           :deadline))))))
398                   'nil)))))
399
400 ;;; semaphores
401
402 (defmacro raises-timeout-p (&body body)
403   `(handler-case (progn (progn ,@body) nil)
404     (sb-ext:timeout () t)))
405
406 (with-test (:name (:semaphore :wait-forever))
407   (let ((sem (make-semaphore :count 0)))
408     (assert (raises-timeout-p
409               (sb-ext:with-timeout 0.1
410                 (wait-on-semaphore sem))))))
411
412 (with-test (:name (:semaphore :initial-count))
413   (let ((sem (make-semaphore :count 1)))
414     (sb-ext:with-timeout 0.1
415       (wait-on-semaphore sem))))
416
417 (with-test (:name (:semaphore :wait-then-signal))
418   (let ((sem (make-semaphore))
419         (signalled-p nil))
420     (make-thread (lambda ()
421                    (sleep 0.1)
422                    (setq signalled-p t)
423                    (signal-semaphore sem)))
424     (wait-on-semaphore sem)
425     (assert signalled-p)))
426
427 (with-test (:name (:semaphore :signal-then-wait))
428   (let ((sem (make-semaphore))
429         (signalled-p nil))
430     (make-thread (lambda ()
431                    (signal-semaphore sem)
432                    (setq signalled-p t)))
433     (loop until signalled-p)
434     (wait-on-semaphore sem)
435     (assert signalled-p)))
436
437 (defun test-semaphore-multiple-signals (wait-on-semaphore)
438   (let* ((sem (make-semaphore :count 5))
439          (threads (loop repeat 20 collecting
440                         (make-thread (lambda ()
441                                        (funcall wait-on-semaphore sem))))))
442     (flet ((count-live-threads ()
443              (count-if #'thread-alive-p threads)))
444       (sleep 0.5)
445       (assert (= 15 (count-live-threads)))
446       (signal-semaphore sem 10)
447       (sleep 0.5)
448       (assert (= 5 (count-live-threads)))
449       (signal-semaphore sem 3)
450       (sleep 0.5)
451       (assert (= 2 (count-live-threads)))
452       (signal-semaphore sem 4)
453       (sleep 0.5)
454       (assert (= 0 (count-live-threads))))))
455
456 (with-test (:name (:semaphore :multiple-signals))
457   (test-semaphore-multiple-signals #'wait-on-semaphore))
458
459 (with-test (:name (:try-semaphore :trivial-fail))
460   (assert (eq (try-semaphore (make-semaphore :count 0)) 'nil)))
461
462 (with-test (:name (:try-semaphore :trivial-success))
463   (let ((sem (make-semaphore :count 1)))
464     (assert (try-semaphore sem))
465     (assert (zerop (semaphore-count sem)))))
466
467 (with-test (:name (:try-semaphore :trivial-fail :n>1))
468   (assert (eq (try-semaphore (make-semaphore :count 1) 2) 'nil)))
469
470 (with-test (:name (:try-semaphore :trivial-success :n>1))
471   (let ((sem (make-semaphore :count 10)))
472     (assert (try-semaphore sem 5))
473     (assert (try-semaphore sem 5))
474     (assert (zerop (semaphore-count sem)))))
475
476 (with-test (:name (:try-semaphore :emulate-wait-on-semaphore))
477   (flet ((busy-wait-on-semaphore (sem)
478            (loop until (try-semaphore sem) do (sleep 0.001))))
479     (test-semaphore-multiple-signals #'busy-wait-on-semaphore)))
480
481 ;;; Here we test that interrupting TRY-SEMAPHORE does not leave a
482 ;;; semaphore in a bad state.
483 (with-test (:name (:try-semaphore :interrupt-safe))
484   (flet ((make-threads (count fn)
485            (loop repeat count collect (make-thread fn)))
486          (kill-thread (thread)
487            (when (thread-alive-p thread)
488              (ignore-errors (terminate-thread thread))))
489          (count-live-threads (threads)
490            (count-if #'thread-alive-p threads)))
491     ;; WAITERS will already be waiting on the semaphore while
492     ;; threads-being-interrupted will perform TRY-SEMAPHORE on that
493     ;; semaphore, and MORE-WAITERS are new threads trying to wait on
494     ;; the semaphore during the interruption-fire.
495     (let* ((sem (make-semaphore :count 100))
496            (waiters (make-threads 20 #'(lambda ()
497                                          (wait-on-semaphore sem))))
498            (triers  (make-threads 40 #'(lambda ()
499                                          (sleep (random 0.01))
500                                          (try-semaphore sem (1+ (random 5))))))
501            (more-waiters
502             (loop repeat 10
503                   do (kill-thread (nth (random 40) triers))
504                   collect (make-thread #'(lambda () (wait-on-semaphore sem)))
505                   do (kill-thread (nth (random 40) triers)))))
506       (sleep 0.5)
507       ;; Now ensure that the waiting threads will all be waked up,
508       ;; i.e. that the semaphore is still working.
509       (loop repeat (+ (count-live-threads waiters)
510                       (count-live-threads more-waiters))
511             do (signal-semaphore sem))
512       (sleep 0.5)
513       (assert (zerop (count-live-threads triers)))
514       (assert (zerop (count-live-threads waiters)))
515       (assert (zerop (count-live-threads more-waiters))))))
516
517
518
519 (format t "~&semaphore tests done~%")
520
521 (defun test-interrupt (function-to-interrupt &optional quit-p)
522   (let ((child  (make-thread function-to-interrupt)))
523     ;;(format t "gdb ./src/runtime/sbcl ~A~%attach ~A~%" child child)
524     (sleep 2)
525     (format t "interrupting child ~A~%" child)
526     (interrupt-thread child
527                       (lambda ()
528                         (format t "child pid ~A~%" *current-thread*)
529                         (when quit-p (sb-ext:quit))))
530     (sleep 1)
531     child))
532
533 ;; separate tests for (a) interrupting Lisp code, (b) C code, (c) a syscall,
534 ;; (d) waiting on a lock, (e) some code which we hope is likely to be
535 ;; in pseudo-atomic
536
537 (with-test (:name (:interrupt-thread :more-basics))
538   (let ((child (test-interrupt (lambda () (loop)))))
539     (terminate-thread child)))
540
541 (with-test (:name (:interrupt-thread :interrupt-foreign-loop))
542   (test-interrupt #'loop-forever :quit))
543
544 (with-test (:name (:interrupt-thread :interrupt-sleep))
545   (let ((child (test-interrupt (lambda () (loop (sleep 2000))))))
546     (terminate-thread child)
547     (wait-for-threads (list child))))
548
549 (with-test (:name (:interrupt-thread :interrupt-mutex-acquisition))
550   (let ((lock (make-mutex :name "loctite"))
551         child)
552     (with-mutex (lock)
553       (setf child (test-interrupt
554                    (lambda ()
555                      (with-mutex (lock)
556                        (assert (eql (mutex-value lock) *current-thread*)))
557                      (assert (not (eql (mutex-value lock) *current-thread*)))
558                      (sleep 10))))
559       ;;hold onto lock for long enough that child can't get it immediately
560       (sleep 5)
561       (interrupt-thread child (lambda () (format t "l ~A~%" (mutex-value lock))))
562       (format t "parent releasing lock~%"))
563     (terminate-thread child)
564     (wait-for-threads (list child))))
565
566 (format t "~&locking test done~%")
567
568 (defun alloc-stuff () (copy-list '(1 2 3 4 5)))
569
570 (with-test (:name (:interrupt-thread :interrupt-consing-child))
571   (let ((thread (sb-thread:make-thread (lambda () (loop (alloc-stuff))))))
572     (let ((killers
573            (loop repeat 4 collect
574                  (sb-thread:make-thread
575                   (lambda ()
576                     (loop repeat 25 do
577                           (sleep (random 0.1d0))
578                           (princ ".")
579                           (force-output)
580                           (sb-thread:interrupt-thread thread (lambda ()))))))))
581       (wait-for-threads killers)
582       (sb-thread:terminate-thread thread)
583       (wait-for-threads (list thread))))
584   (sb-ext:gc :full t))
585
586 (format t "~&multi interrupt test done~%")
587
588 #+(or x86 x86-64) ;; x86oid-only, see internal commentary.
589 (with-test (:name (:interrupt-thread :interrupt-consing-child :again))
590   (let ((c (make-thread (lambda () (loop (alloc-stuff))))))
591     ;; NB this only works on x86: other ports don't have a symbol for
592     ;; pseudo-atomic atomicity
593     (dotimes (i 100)
594       (sleep (random 0.1d0))
595       (interrupt-thread c
596                         (lambda ()
597                           (princ ".") (force-output)
598                           (assert (thread-alive-p *current-thread*))
599                           (assert
600                            (not (logbitp 0 SB-KERNEL:*PSEUDO-ATOMIC-BITS*))))))
601     (terminate-thread c)
602     (wait-for-threads (list c))))
603
604 (format t "~&interrupt test done~%")
605
606 (defstruct counter (n 0 :type sb-vm:word))
607 (defvar *interrupt-counter* (make-counter))
608
609 (declaim (notinline check-interrupt-count))
610 (defun check-interrupt-count (i)
611   (declare (optimize (debug 1) (speed 1)))
612   ;; This used to lose if eflags were not restored after an interrupt.
613   (unless (typep i 'fixnum)
614     (error "!!!!!!!!!!!")))
615
616 (with-test (:name (:interrupt-thread :interrupt-ATOMIC-INCF))
617   (let ((c (make-thread
618             (lambda ()
619               (handler-bind ((error #'(lambda (cond)
620                                         (princ cond)
621                                         (sb-debug:backtrace
622                                          most-positive-fixnum))))
623                 (loop (check-interrupt-count
624                        (counter-n *interrupt-counter*))))))))
625     (let ((func (lambda ()
626                   (princ ".")
627                   (force-output)
628                   (sb-ext:atomic-incf (counter-n *interrupt-counter*)))))
629       (setf (counter-n *interrupt-counter*) 0)
630       (dotimes (i 100)
631         (sleep (random 0.1d0))
632         (interrupt-thread c func))
633       (loop until (= (counter-n *interrupt-counter*) 100) do (sleep 0.1))
634       (terminate-thread c)
635       (wait-for-threads (list c)))))
636
637 (format t "~&interrupt count test done~%")
638
639 (defvar *runningp* nil)
640
641 (with-test (:name (:interrupt-thread :no-nesting))
642   (let ((thread (sb-thread:make-thread
643                  (lambda ()
644                    (catch 'xxx
645                      (loop))))))
646     (declare (special runningp))
647     (sleep 0.2)
648     (sb-thread:interrupt-thread thread
649                                 (lambda ()
650                                     (let ((*runningp* t))
651                                       (sleep 1))))
652     (sleep 0.2)
653     (sb-thread:interrupt-thread thread
654                                 (lambda ()
655                                   (throw 'xxx *runningp*)))
656     (assert (not (sb-thread:join-thread thread)))))
657
658 (with-test (:name (:interrupt-thread :nesting))
659   (let ((thread (sb-thread:make-thread
660                  (lambda ()
661                    (catch 'xxx
662                      (loop))))))
663     (declare (special runningp))
664     (sleep 0.2)
665     (sb-thread:interrupt-thread thread
666                                 (lambda ()
667                                   (let ((*runningp* t))
668                                     (sb-sys:with-interrupts
669                                       (sleep 1)))))
670     (sleep 0.2)
671     (sb-thread:interrupt-thread thread
672                                 (lambda ()
673                                   (throw 'xxx *runningp*)))
674     (assert (sb-thread:join-thread thread))))
675
676 (with-test (:name (:two-threads-running-gc))
677   (let (a-done b-done)
678     (make-thread (lambda ()
679                    (dotimes (i 100)
680                      (sb-ext:gc) (princ "\\") (force-output))
681                    (setf a-done t)))
682     (make-thread (lambda ()
683                    (dotimes (i 25)
684                      (sb-ext:gc :full t)
685                      (princ "/") (force-output))
686                    (setf b-done t)))
687     (loop
688       (when (and a-done b-done) (return))
689       (sleep 1))))
690
691 (terpri)
692
693 (defun waste (&optional (n 100000))
694   (loop repeat n do (make-string 16384)))
695
696 (with-test (:name (:one-thread-runs-gc-while-other-conses))
697   (loop for i below 100 do
698         (princ "!")
699         (force-output)
700         (sb-thread:make-thread
701          #'(lambda ()
702              (waste)))
703         (waste)
704         (sb-ext:gc)))
705
706 (terpri)
707
708 (defparameter *aaa* nil)
709 (with-test (:name (:one-thread-runs-gc-while-other-conses :again))
710   (loop for i below 100 do
711         (princ "!")
712         (force-output)
713         (sb-thread:make-thread
714          #'(lambda ()
715              (let ((*aaa* (waste)))
716                (waste))))
717         (let ((*aaa* (waste)))
718           (waste))
719         (sb-ext:gc)))
720
721 (format t "~&gc test done~%")
722
723 ;; this used to deadlock on session-lock
724 (with-test (:name (:no-session-deadlock))
725   (sb-thread:make-thread (lambda () (sb-ext:gc))))
726
727 (defun exercise-syscall (fn reference-errno)
728   (sb-thread:make-thread
729    (lambda ()
730      (loop do
731           (funcall fn)
732           (let ((errno (sb-unix::get-errno)))
733             (sleep (random 0.1d0))
734             (unless (eql errno reference-errno)
735               (format t "Got errno: ~A (~A) instead of ~A~%"
736                       errno
737                       (sb-unix::strerror)
738                       reference-errno)
739               (force-output)
740               (sb-ext:quit :unix-status 1)))))))
741
742 ;; (nanosleep -1 0) does not fail on FreeBSD
743 (with-test (:name (:exercising-concurrent-syscalls))
744   (let* (#-freebsd
745          (nanosleep-errno (progn
746                             (sb-unix:nanosleep -1 0)
747                             (sb-unix::get-errno)))
748          (open-errno (progn
749                        (open "no-such-file"
750                              :if-does-not-exist nil)
751                        (sb-unix::get-errno)))
752          (threads
753           (list
754            #-freebsd
755            (exercise-syscall (lambda () (sb-unix:nanosleep -1 0)) nanosleep-errno)
756            (exercise-syscall (lambda () (open "no-such-file"
757                                               :if-does-not-exist nil))
758                              open-errno)
759            (sb-thread:make-thread (lambda () (loop (sb-ext:gc) (sleep 1)))))))
760     (sleep 10)
761     (princ "terminating threads")
762     (dolist (thread threads)
763       (sb-thread:terminate-thread thread))))
764
765 (format t "~&errno test done~%")
766
767 (with-test (:name (:terminate-thread-restart))
768   (loop repeat 100 do
769         (let ((thread (sb-thread:make-thread (lambda () (sleep 0.1)))))
770           (sb-thread:interrupt-thread
771            thread
772            (lambda ()
773              (assert (find-restart 'sb-thread:terminate-thread)))))))
774
775 (sb-ext:gc :full t)
776
777 (format t "~&thread startup sigmask test done~%")
778
779 (with-test (:name (:debugger-no-hang-on-session-lock-if-interrupted))
780   (sb-debug::enable-debugger)
781   (let* ((main-thread *current-thread*)
782          (interruptor-thread
783           (make-thread (lambda ()
784                          (sleep 2)
785                          (interrupt-thread main-thread
786                                            (lambda ()
787                                              (with-interrupts
788                                                (break))))
789                          (sleep 2)
790                          (interrupt-thread main-thread #'continue))
791                        :name "interruptor")))
792     (with-session-lock (*session*)
793       (sleep 3))
794     (loop while (thread-alive-p interruptor-thread))))
795
796 (format t "~&session lock test done~%")
797
798 ;; expose thread creation races by exiting quickly
799 (with-test (:name (:no-thread-creation-race :light))
800   (sb-thread:make-thread (lambda ())))
801
802 (with-test (:name (:no-thread-creation-race :heavy))
803   (loop repeat 20 do
804         (wait-for-threads
805          (loop for i below 100 collect
806                (sb-thread:make-thread (lambda ()))))))
807
808 (format t "~&creation test done~%")
809
810 ;; interrupt handlers are per-thread with pthreads, make sure the
811 ;; handler installed in one thread is global
812 (with-test (:name (:global-interrupt-handler))
813   (sb-thread:make-thread
814    (lambda ()
815      (sb-ext:run-program "sleep" '("1") :search t :wait nil))))
816
817 ;;;; Binding stack safety
818
819 (defparameter *x* nil)
820 (defparameter *n-gcs-requested* 0)
821 (defparameter *n-gcs-done* 0)
822
823 (let ((counter 0))
824   (defun make-something-big ()
825     (let ((x (make-string 32000)))
826       (incf counter)
827       (let ((counter counter))
828         (sb-ext:finalize x (lambda () (format t " ~S" counter)
829                                    (force-output)))))))
830
831 (defmacro wait-for-gc ()
832   `(progn
833      (incf *n-gcs-requested*)
834      (loop while (< *n-gcs-done* *n-gcs-requested*))))
835
836 (defun send-gc ()
837   (loop until (< *n-gcs-done* *n-gcs-requested*))
838   (format t "G")
839   (force-output)
840   (sb-ext:gc)
841   (incf *n-gcs-done*))
842
843 (defun exercise-binding ()
844   (loop
845    (let ((*x* (make-something-big)))
846      (let ((*x* 42))
847        ;; at this point the binding stack looks like this:
848        ;; NO-TLS-VALUE-MARKER, *x*, SOMETHING, *x*
849        t))
850    (wait-for-gc)
851    ;; sig_stop_for_gc_handler binds FREE_INTERRUPT_CONTEXT_INDEX. By
852    ;; now SOMETHING is gc'ed and the binding stack looks like this: 0,
853    ;; 0, SOMETHING, 0 (because the symbol slots are zeroed on
854    ;; unbinding but values are not).
855    (let ((*x* nil)
856          (binding-pointer-delta (ash 2 (- sb-vm:word-shift sb-vm:n-fixnum-tag-bits))))
857      ;; bump bsp as if a BIND had just started
858      (incf sb-vm::*binding-stack-pointer* binding-pointer-delta)
859      (wait-for-gc)
860      (decf sb-vm::*binding-stack-pointer* binding-pointer-delta))))
861
862 (with-test (:name (:binding-stack-gc-safety))
863   (let (threads)
864     (unwind-protect
865          (progn
866            (push (sb-thread:make-thread #'exercise-binding) threads)
867            (push (sb-thread:make-thread (lambda ()
868                                           (loop
869                                            (sleep 0.1)
870                                            (send-gc))))
871                  threads)
872            (sleep 4))
873       (mapc #'sb-thread:terminate-thread threads))))
874
875 (format t "~&binding test done~%")
876
877 ;;; HASH TABLES
878
879 (defvar *errors* nil)
880
881 (defun oops (e)
882   (setf *errors* e)
883   (format t "~&oops: ~A in ~S~%" e *current-thread*)
884   (sb-debug:backtrace)
885   (catch 'done))
886
887 (with-test (:name (:unsynchronized-hash-table)
888                   ;; FIXME: This test occasionally eats out craploads
889                   ;; of heap instead of expected error early. Not 100%
890                   ;; sure if it would finish as expected, but since it
891                   ;; hits swap on my system I'm not likely to find out
892                   ;; soon. Disabling for now. -- nikodemus
893             :skipped-on :sbcl)
894   ;; We expect a (probable) error here: parellel readers and writers
895   ;; on a hash-table are not expected to work -- but we also don't
896   ;; expect this to corrupt the image.
897   (let* ((hash (make-hash-table))
898          (*errors* nil)
899          (threads (list (sb-thread:make-thread
900                          (lambda ()
901                            (catch 'done
902                              (handler-bind ((serious-condition 'oops))
903                                (loop
904                                  ;;(princ "1") (force-output)
905                                  (setf (gethash (random 100) hash) 'h)))))
906                          :name "writer")
907                         (sb-thread:make-thread
908                          (lambda ()
909                            (catch 'done
910                              (handler-bind ((serious-condition 'oops))
911                                (loop
912                                  ;;(princ "2") (force-output)
913                                  (remhash (random 100) hash)))))
914                          :name "reader")
915                         (sb-thread:make-thread
916                          (lambda ()
917                            (catch 'done
918                              (handler-bind ((serious-condition 'oops))
919                                (loop
920                                  (sleep (random 1.0))
921                                  (sb-ext:gc :full t)))))
922                          :name "collector"))))
923     (unwind-protect
924          (sleep 10)
925       (mapc #'sb-thread:terminate-thread threads))))
926
927 (format t "~&unsynchronized hash table test done~%")
928
929 (with-test (:name (:synchronized-hash-table))
930   (let* ((hash (make-hash-table :synchronized t))
931          (*errors* nil)
932          (threads (list (sb-thread:make-thread
933                          (lambda ()
934                            (catch 'done
935                              (handler-bind ((serious-condition 'oops))
936                                (loop
937                                  ;;(princ "1") (force-output)
938                                  (setf (gethash (random 100) hash) 'h)))))
939                          :name "writer")
940                         (sb-thread:make-thread
941                          (lambda ()
942                            (catch 'done
943                              (handler-bind ((serious-condition 'oops))
944                                (loop
945                                  ;;(princ "2") (force-output)
946                                  (remhash (random 100) hash)))))
947                          :name "reader")
948                         (sb-thread:make-thread
949                          (lambda ()
950                            (catch 'done
951                              (handler-bind ((serious-condition 'oops))
952                                (loop
953                                  (sleep (random 1.0))
954                                  (sb-ext:gc :full t)))))
955                          :name "collector"))))
956     (unwind-protect
957          (sleep 10)
958       (mapc #'sb-thread:terminate-thread threads))
959     (assert (not *errors*))))
960
961 (format t "~&synchronized hash table test done~%")
962
963 (with-test (:name (:hash-table-parallel-readers))
964   (let ((hash (make-hash-table))
965         (*errors* nil))
966     (loop repeat 50
967           do (setf (gethash (random 100) hash) 'xxx))
968     (let ((threads (list (sb-thread:make-thread
969                           (lambda ()
970                             (catch 'done
971                               (handler-bind ((serious-condition 'oops))
972                                 (loop
973                                       until (eq t (gethash (random 100) hash))))))
974                           :name "reader 1")
975                          (sb-thread:make-thread
976                           (lambda ()
977                             (catch 'done
978                               (handler-bind ((serious-condition 'oops))
979                                 (loop
980                                       until (eq t (gethash (random 100) hash))))))
981                           :name "reader 2")
982                          (sb-thread:make-thread
983                           (lambda ()
984                             (catch 'done
985                               (handler-bind ((serious-condition 'oops))
986                                 (loop
987                                       until (eq t (gethash (random 100) hash))))))
988                           :name "reader 3")
989                          (sb-thread:make-thread
990                           (lambda ()
991                             (catch 'done
992                               (handler-bind ((serious-condition 'oops))
993                                (loop
994                                  (sleep (random 1.0))
995                                  (sb-ext:gc :full t)))))
996                           :name "collector"))))
997       (unwind-protect
998            (sleep 10)
999         (mapc #'sb-thread:terminate-thread threads))
1000       (assert (not *errors*)))))
1001
1002 (format t "~&multiple reader hash table test done~%")
1003
1004 (with-test (:name (:hash-table-single-accessor-parallel-gc))
1005   (let ((hash (make-hash-table))
1006         (*errors* nil))
1007     (let ((threads (list (sb-thread:make-thread
1008                           (lambda ()
1009                             (handler-bind ((serious-condition 'oops))
1010                               (loop
1011                                 (let ((n (random 100)))
1012                                   (if (gethash n hash)
1013                                       (remhash n hash)
1014                                       (setf (gethash n hash) 'h))))))
1015                           :name "accessor")
1016                          (sb-thread:make-thread
1017                           (lambda ()
1018                             (handler-bind ((serious-condition 'oops))
1019                               (loop
1020                                 (sleep (random 1.0))
1021                                 (sb-ext:gc :full t))))
1022                           :name "collector"))))
1023       (unwind-protect
1024            (sleep 10)
1025         (mapc #'sb-thread:terminate-thread threads))
1026       (assert (not *errors*)))))
1027
1028 (format t "~&single accessor hash table test~%")
1029
1030 #|  ;; a cll post from eric marsden
1031 | (defun crash ()
1032 |   (setq *debugger-hook*
1033 |         (lambda (condition old-debugger-hook)
1034 |           (debug:backtrace 10)
1035 |           (unix:unix-exit 2)))
1036 |   #+live-dangerously
1037 |   (mp::start-sigalrm-yield)
1038 |   (flet ((roomy () (loop (with-output-to-string (*standard-output*) (room)))))
1039 |     (mp:make-process #'roomy)
1040 |     (mp:make-process #'roomy)))
1041 |#
1042
1043 (with-test (:name (:condition-variable :notify-multiple))
1044   (flet ((tester (notify-fun)
1045            (let ((queue (make-waitqueue :name "queue"))
1046                  (lock (make-mutex :name "lock"))
1047                  (data nil))
1048              (labels ((test (x)
1049                         (loop
1050                            (with-mutex (lock)
1051                              (format t "condition-wait ~a~%" x)
1052                              (force-output)
1053                              (condition-wait queue lock)
1054                              (format t "woke up ~a~%" x)
1055                              (force-output)
1056                              (push x data)))))
1057                (let ((threads (loop for x from 1 to 10
1058                                     collect
1059                                     (let ((x x))
1060                                       (sb-thread:make-thread (lambda ()
1061                                                                (test x)))))))
1062                  (sleep 5)
1063                  (with-mutex (lock)
1064                    (funcall notify-fun queue))
1065                  (sleep 5)
1066                  (mapcar #'terminate-thread threads)
1067                  ;; Check that all threads woke up at least once
1068                  (assert (= (length (remove-duplicates data)) 10)))))))
1069     (tester (lambda (queue)
1070               (format t "~&(condition-notify queue 10)~%")
1071               (force-output)
1072               (condition-notify queue 10)))
1073     (tester (lambda (queue)
1074               (format t "~&(condition-broadcast queue)~%")
1075               (force-output)
1076               (condition-broadcast queue)))))
1077
1078 (format t "waitqueue wakeup tests done~%")
1079
1080 ;;; Make sure that a deadline handler is not invoked twice in a row in
1081 ;;; CONDITION-WAIT. See LP #512914 for a detailed explanation.
1082 ;;;
1083 #-sb-lutex    ; See KLUDGE above: no deadlines for condition-wait+lutexes.
1084 (with-test (:name (:condition-wait :deadlines :LP-512914))
1085   (let ((n 2) ; was empirically enough to trigger the bug
1086         (mutex (sb-thread:make-mutex))
1087         (waitq (sb-thread:make-waitqueue))
1088         (threads nil)
1089         (deadline-handler-run-twice? nil))
1090     (dotimes (i n)
1091       (let ((child
1092              (sb-thread:make-thread
1093               #'(lambda ()
1094                   (handler-bind
1095                       ((sb-sys:deadline-timeout
1096                         (let ((already? nil))
1097                           #'(lambda (c)
1098                               (when already?
1099                                 (setq deadline-handler-run-twice? t))
1100                               (setq already? t)
1101                               (sleep 0.2)
1102                               (sb-thread:condition-broadcast waitq)
1103                               (sb-sys:defer-deadline 10.0 c)))))
1104                     (sb-sys:with-deadline (:seconds 0.1)
1105                       (sb-thread:with-mutex (mutex)
1106                         (sb-thread:condition-wait waitq mutex))))))))
1107         (push child threads)))
1108     (mapc #'sb-thread:join-thread threads)
1109     (assert (not deadline-handler-run-twice?))))
1110
1111 (with-test (:name (:condition-wait :signal-deadline-with-interrupts-enabled))
1112   #+darwin
1113   (error "Bad Darwin")
1114   (let ((mutex (sb-thread:make-mutex))
1115         (waitq (sb-thread:make-waitqueue))
1116         (A-holds? :unknown)
1117         (B-holds? :unknown)
1118         (A-interrupts-enabled? :unknown)
1119         (B-interrupts-enabled? :unknown)
1120         (A)
1121         (B))
1122     ;; W.L.O.G., we assume that A is executed first...
1123     (setq A (sb-thread:make-thread
1124              #'(lambda ()
1125                  (handler-bind
1126                      ((sb-sys:deadline-timeout
1127                        #'(lambda (c)
1128                            ;; We came here through the call to DECODE-TIMEOUT
1129                            ;; in CONDITION-WAIT; hence both here are supposed
1130                            ;; to evaluate to T.
1131                            (setq A-holds? (sb-thread:holding-mutex-p mutex))
1132                            (setq A-interrupts-enabled?
1133                                  sb-sys:*interrupts-enabled*)
1134                            (sleep 0.2)
1135                            (sb-thread:condition-broadcast waitq)
1136                            (sb-sys:defer-deadline 10.0 c))))
1137                    (sb-sys:with-deadline (:seconds 0.1)
1138                      (sb-thread:with-mutex (mutex)
1139                        (sb-thread:condition-wait waitq mutex)))))))
1140     (setq B (sb-thread:make-thread
1141              #'(lambda ()
1142                  (thread-yield)
1143                  (handler-bind
1144                      ((sb-sys:deadline-timeout
1145                        #'(lambda (c)
1146                            ;; We came here through the call to GET-MUTEX
1147                            ;; in CONDITION-WAIT (contended case of
1148                            ;; reaquiring the mutex) - so the former will
1149                            ;; be NIL, but interrupts should still be enabled.
1150                            (setq B-holds? (sb-thread:holding-mutex-p mutex))
1151                            (setq B-interrupts-enabled?
1152                                  sb-sys:*interrupts-enabled*)
1153                            (sleep 0.2)
1154                            (sb-thread:condition-broadcast waitq)
1155                            (sb-sys:defer-deadline 10.0 c))))
1156                    (sb-sys:with-deadline (:seconds 0.1)
1157                      (sb-thread:with-mutex (mutex)
1158                        (sb-thread:condition-wait waitq mutex)))))))
1159     (sb-thread:join-thread A)
1160     (sb-thread:join-thread B)
1161     (let ((A-result (list A-holds? A-interrupts-enabled?))
1162           (B-result (list B-holds? B-interrupts-enabled?)))
1163       ;; We also check some subtle behaviour w.r.t. whether a deadline
1164       ;; handler in CONDITION-WAIT got the mutex, or not. This is most
1165       ;; probably very internal behaviour (so user should not depend
1166       ;; on it) -- I added the testing here just to manifest current
1167       ;; behaviour.
1168       (cond ((equal A-result '(t t)) (assert (equal B-result '(nil t))))
1169             ((equal B-result '(t t)) (assert (equal A-result '(nil t))))
1170             (t (error "Failure: fall through."))))))
1171
1172 (with-test (:name (:mutex :finalization))
1173   (let ((a nil))
1174     (dotimes (i 500000)
1175       (setf a (make-mutex)))))
1176
1177 (format t "mutex finalization test done~%")
1178
1179 ;;; Check that INFO is thread-safe, at least when we're just doing reads.
1180
1181 (let* ((symbols (loop repeat 10000 collect (gensym)))
1182        (functions (loop for (symbol . rest) on symbols
1183                         for next = (car rest)
1184                         for fun = (let ((next next))
1185                                     (lambda (n)
1186                                       (if next
1187                                           (funcall next (1- n))
1188                                           n)))
1189                         do (setf (symbol-function symbol) fun)
1190                         collect fun)))
1191   (defun infodb-test ()
1192     (funcall (car functions) 9999)))
1193
1194 (with-test (:name (:infodb :read))
1195   (let* ((ok t)
1196          (threads (loop for i from 0 to 10
1197                         collect (sb-thread:make-thread
1198                                  (lambda ()
1199                                    (dotimes (j 100)
1200                                      (write-char #\-)
1201                                      (finish-output)
1202                                      (let ((n (infodb-test)))
1203                                        (unless (zerop n)
1204                                          (setf ok nil)
1205                                          (format t "N != 0 (~A)~%" n)
1206                                          (sb-ext:quit)))))))))
1207     (wait-for-threads threads)
1208     (assert ok)))
1209
1210 (format t "infodb test done~%")
1211
1212 (with-test (:name (:backtrace))
1213   #+darwin
1214   (error "Prone to crash on Darwin, cause unknown.")
1215   ;; Printing backtraces from several threads at once used to hang the
1216   ;; whole SBCL process (discovered by accident due to a timer.impure
1217   ;; test misbehaving). The cause was that packages weren't even
1218   ;; thread-safe for only doing FIND-SYMBOL, and while printing
1219   ;; backtraces a loot of symbol lookups need to be done due to
1220   ;; *PRINT-ESCAPE*.
1221   (let* ((threads (loop repeat 10
1222                         collect (sb-thread:make-thread
1223                                  (lambda ()
1224                                    (dotimes (i 1000)
1225                                      (with-output-to-string (*debug-io*)
1226                                        (sb-debug::backtrace 10))))))))
1227     (wait-for-threads threads)))
1228
1229 (format t "backtrace test done~%")
1230
1231 (format t "~&starting gc deadlock test: WARNING: THIS TEST WILL HANG ON FAILURE!~%")
1232
1233 (with-test (:name (:gc-deadlock))
1234   #+darwin
1235   (error "Prone to hang on Darwin due to interrupt issues.")
1236   ;; Prior to 0.9.16.46 thread exit potentially deadlocked the
1237   ;; GC due to *all-threads-lock* and session lock. On earlier
1238   ;; versions and at least on one specific box this test is good enough
1239   ;; to catch that typically well before the 1500th iteration.
1240   (loop
1241      with i = 0
1242      with n = 3000
1243      while (< i n)
1244      do
1245        (incf i)
1246        (when (zerop (mod i 100))
1247          (write-char #\.)
1248          (force-output))
1249        (handler-case
1250            (if (oddp i)
1251                (sb-thread:make-thread
1252                 (lambda ()
1253                   (sleep (random 0.001)))
1254                 :name (format nil "SLEEP-~D" i))
1255                (sb-thread:make-thread
1256                 (lambda ()
1257                   ;; KLUDGE: what we are doing here is explicit,
1258                   ;; but the same can happen because of a regular
1259                   ;; MAKE-THREAD or LIST-ALL-THREADS, and various
1260                   ;; session functions.
1261                   (sb-thread::with-all-threads-lock
1262                     (sb-thread::with-session-lock (sb-thread::*session*)
1263                       (sb-ext:gc))))
1264                 :name (format nil "GC-~D" i)))
1265          (error (e)
1266            (format t "~%error creating thread ~D: ~A -- backing off for retry~%" i e)
1267            (sleep 0.1)
1268            (incf i)))))
1269
1270 (format t "~&gc deadlock test done~%")
1271 \f
1272 (let ((count (make-array 8 :initial-element 0)))
1273   (defun closure-one ()
1274     (declare (optimize safety))
1275     (values (incf (aref count 0)) (incf (aref count 1))
1276             (incf (aref count 2)) (incf (aref count 3))
1277             (incf (aref count 4)) (incf (aref count 5))
1278             (incf (aref count 6)) (incf (aref count 7))))
1279   (defun no-optimizing-away-closure-one ()
1280     (setf count (make-array 8 :initial-element 0))))
1281
1282 (defstruct box
1283   (count 0))
1284
1285 (let ((one (make-box))
1286       (two (make-box))
1287       (three (make-box)))
1288   (defun closure-two ()
1289     (declare (optimize safety))
1290     (values (incf (box-count one)) (incf (box-count two)) (incf (box-count three))))
1291   (defun no-optimizing-away-closure-two ()
1292     (setf one (make-box)
1293           two (make-box)
1294           three (make-box))))
1295
1296 (with-test (:name (:funcallable-instances))
1297   ;; the funcallable-instance implementation used not to be threadsafe
1298   ;; against setting the funcallable-instance function to a closure
1299   ;; (because the code and lexenv were set separately).
1300   (let ((fun (sb-kernel:%make-funcallable-instance 0))
1301         (condition nil))
1302     (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
1303     (flet ((changer ()
1304              (loop (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
1305                    (setf (sb-kernel:funcallable-instance-fun fun) #'closure-two)))
1306            (test ()
1307              (handler-case (loop (funcall fun))
1308                (serious-condition (c) (setf condition c)))))
1309       (let ((changer (make-thread #'changer))
1310             (test (make-thread #'test)))
1311         (handler-case
1312             (progn
1313               ;; The two closures above are fairly carefully crafted
1314               ;; so that if given the wrong lexenv they will tend to
1315               ;; do some serious damage, but it is of course difficult
1316               ;; to predict where the various bits and pieces will be
1317               ;; allocated.  Five seconds failed fairly reliably on
1318               ;; both my x86 and x86-64 systems.  -- CSR, 2006-09-27.
1319               (sb-ext:with-timeout 5
1320                 (wait-for-threads (list test)))
1321               (error "~@<test thread got condition:~2I~_~A~@:>" condition))
1322           (sb-ext:timeout ()
1323             (terminate-thread changer)
1324             (terminate-thread test)
1325             (wait-for-threads (list changer test))))))))
1326
1327 (format t "~&funcallable-instance test done~%")
1328
1329 (defun random-type (n)
1330   `(integer ,(random n) ,(+ n (random n))))
1331
1332 (defun subtypep-hash-cache-test ()
1333   (dotimes (i 10000)
1334     (let ((type1 (random-type 500))
1335           (type2 (random-type 500)))
1336       (let ((a (subtypep type1 type2)))
1337         (dotimes (i 100)
1338           (assert (eq (subtypep type1 type2) a))))))
1339   (format t "ok~%")
1340   (force-output))
1341
1342 (with-test (:name (:hash-cache :subtypep))
1343   (dotimes (i 10)
1344     (sb-thread:make-thread #'subtypep-hash-cache-test)))
1345 (format t "hash-cache tests done~%")
1346
1347 ;;;; BLACK BOX TESTS
1348
1349 (in-package :cl-user)
1350 (use-package :test-util)
1351 (use-package "ASSERTOID")
1352
1353 (format t "parallel defclass test -- WARNING, WILL HANG ON FAILURE!~%")
1354 (with-test (:name :parallel-defclass)
1355   (defclass test-1 () ((a :initform :orig-a)))
1356   (defclass test-2 () ((b :initform :orig-b)))
1357   (defclass test-3 (test-1 test-2) ((c :initform :orig-c)))
1358   (let* ((run t)
1359          (d1 (sb-thread:make-thread (lambda ()
1360                                       (loop while run
1361                                             do (defclass test-1 () ((a :initform :new-a)))
1362                                             (write-char #\1)
1363                                             (force-output)))
1364                                     :name "d1"))
1365          (d2 (sb-thread:make-thread (lambda ()
1366                                       (loop while run
1367                                             do (defclass test-2 () ((b :initform :new-b)))
1368                                                (write-char #\2)
1369                                                (force-output)))
1370                                     :name "d2"))
1371          (d3 (sb-thread:make-thread (lambda ()
1372                                       (loop while run
1373                                             do (defclass test-3 (test-1 test-2) ((c :initform :new-c)))
1374                                                (write-char #\3)
1375                                                (force-output)))
1376                                     :name "d3"))
1377          (i (sb-thread:make-thread (lambda ()
1378                                      (loop while run
1379                                            do (let ((i (make-instance 'test-3)))
1380                                                 (assert (member (slot-value i 'a) '(:orig-a :new-a)))
1381                                                 (assert (member (slot-value i 'b) '(:orig-b :new-b)))
1382                                                 (assert (member (slot-value i 'c) '(:orig-c :new-c))))
1383                                               (write-char #\i)
1384                                               (force-output)))
1385                                    :name "i")))
1386     (format t "~%sleeping!~%")
1387     (sleep 2.0)
1388     (format t "~%stopping!~%")
1389     (setf run nil)
1390     (mapc (lambda (th)
1391             (sb-thread:join-thread th)
1392             (format t "~%joined ~S~%" (sb-thread:thread-name th)))
1393           (list d1 d2 d3 i))))
1394 (format t "parallel defclass test done~%")
1395
1396 (with-test (:name (:deadlock-detection :interrupts))
1397   (let* ((m1 (sb-thread:make-mutex :name "M1"))
1398          (m2 (sb-thread:make-mutex :name "M2"))
1399          (t1 (sb-thread:make-thread
1400               (lambda ()
1401                 (sb-thread:with-mutex (m1)
1402                   (sleep 0.3)
1403                   :ok))
1404               :name "T1"))
1405          (t2 (sb-thread:make-thread
1406               (lambda ()
1407                 (sleep 0.1)
1408                 (sb-thread:with-mutex (m1 :wait-p t)
1409                   (sleep 0.2)
1410                   :ok))
1411               :name "T2")))
1412     (sleep 0.2)
1413     (sb-thread:interrupt-thread t2 (lambda ()
1414                                      (sb-thread:with-mutex (m2 :wait-p t)
1415                                        (sleep 0.3))))
1416     (sleep 0.05)
1417     (sb-thread:interrupt-thread t1 (lambda ()
1418                                      (sb-thread:with-mutex (m2 :wait-p t)
1419                                        (sleep 0.3))))
1420     ;; both threads should finish without a deadlock or deadlock
1421     ;; detection error
1422     (let ((res (list (sb-thread:join-thread t1)
1423                      (sb-thread:join-thread t2))))
1424       (assert (equal '(:ok :ok) res)))))
1425
1426 (with-test (:name (:deadlock-detection :gc))
1427   ;; To semi-reliably trigger the error (in SBCL's where)
1428   ;; it was present you had to run this for > 30 seconds,
1429   ;; but that's a bit long for a single test.
1430   (let* ((stop (+ 5 (get-universal-time)))
1431          (m1 (sb-thread:make-mutex :name "m1"))
1432          (t1 (sb-thread:make-thread
1433               (lambda ()
1434                 (loop until (> (get-universal-time) stop)
1435                       do (sb-thread:with-mutex (m1)
1436                            (eval `(make-array 24))))
1437                 :ok)))
1438          (t2 (sb-thread:make-thread
1439               (lambda ()
1440                 (loop until (> (get-universal-time) stop)
1441                       do (sb-thread:with-mutex (m1)
1442                            (eval `(make-array 24))))
1443                 :ok))))
1444     (let ((res (list (sb-thread:join-thread t1)
1445                      (sb-thread:join-thread t2))))
1446       (assert (equal '(:ok :ok) res)))))