1.0.47.29: reinstate Darwin interrupt tests that now succeed
[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     (with-mutex (m)
349       (assert (null (join-thread (make-thread
350                                   #'(lambda ()
351                                       (grab-mutex m :timeout 0.1)))))))))
352
353 (with-test (:name (:grab-mutex :timeout :acquisition-success))
354   #+sb-lutex
355   (error "Mutex timeout not supported here.")
356   (let ((m (make-mutex))
357         (child))
358     (with-mutex (m)
359       (setq child (make-thread #'(lambda () (grab-mutex m :timeout 1.0))))
360       (sleep 0.2))
361     (assert (eq (join-thread child) 't))))
362
363 (with-test (:name (:grab-mutex :timeout+deadline))
364   #+sb-lutex
365   (error "Mutex timeout not supported here.")
366   (let ((m (make-mutex)))
367     (with-mutex (m)
368       (assert (eq (join-thread
369                    (make-thread #'(lambda ()
370                                     (sb-sys:with-deadline (:seconds 0.0)
371                                       (handler-case
372                                           (grab-mutex m :timeout 0.0)
373                                         (sb-sys:deadline-timeout ()
374                                           :deadline))))))
375                   :deadline)))))
376
377 (with-test (:name (:grab-mutex :waitp+deadline))
378   #+sb-lutex
379   (error "Mutex timeout not supported here.")
380   (let ((m (make-mutex)))
381     (with-mutex (m)
382       (assert (eq (join-thread
383                    (make-thread #'(lambda ()
384                                     (sb-sys:with-deadline (:seconds 0.0)
385                                       (handler-case
386                                           (grab-mutex m :waitp nil)
387                                         (sb-sys:deadline-timeout ()
388                                           :deadline))))))
389                   'nil)))))
390
391 ;;; semaphores
392
393 (defmacro raises-timeout-p (&body body)
394   `(handler-case (progn (progn ,@body) nil)
395     (sb-ext:timeout () t)))
396
397 (with-test (:name (:semaphore :wait-forever))
398   (let ((sem (make-semaphore :count 0)))
399     (assert (raises-timeout-p
400               (sb-ext:with-timeout 0.1
401                 (wait-on-semaphore sem))))))
402
403 (with-test (:name (:semaphore :initial-count))
404   (let ((sem (make-semaphore :count 1)))
405     (sb-ext:with-timeout 0.1
406       (wait-on-semaphore sem))))
407
408 (with-test (:name (:semaphore :wait-then-signal))
409   (let ((sem (make-semaphore))
410         (signalled-p nil))
411     (make-thread (lambda ()
412                    (sleep 0.1)
413                    (setq signalled-p t)
414                    (signal-semaphore sem)))
415     (wait-on-semaphore sem)
416     (assert signalled-p)))
417
418 (with-test (:name (:semaphore :signal-then-wait))
419   (let ((sem (make-semaphore))
420         (signalled-p nil))
421     (make-thread (lambda ()
422                    (signal-semaphore sem)
423                    (setq signalled-p t)))
424     (loop until signalled-p)
425     (wait-on-semaphore sem)
426     (assert signalled-p)))
427
428 (defun test-semaphore-multiple-signals (wait-on-semaphore)
429   (let* ((sem (make-semaphore :count 5))
430          (threads (loop repeat 20 collecting
431                         (make-thread (lambda ()
432                                        (funcall wait-on-semaphore sem))))))
433     (flet ((count-live-threads ()
434              (count-if #'thread-alive-p threads)))
435       (sleep 0.5)
436       (assert (= 15 (count-live-threads)))
437       (signal-semaphore sem 10)
438       (sleep 0.5)
439       (assert (= 5 (count-live-threads)))
440       (signal-semaphore sem 3)
441       (sleep 0.5)
442       (assert (= 2 (count-live-threads)))
443       (signal-semaphore sem 4)
444       (sleep 0.5)
445       (assert (= 0 (count-live-threads))))))
446
447 (with-test (:name (:semaphore :multiple-signals))
448   (test-semaphore-multiple-signals #'wait-on-semaphore))
449
450 (with-test (:name (:try-semaphore :trivial-fail))
451   (assert (eq (try-semaphore (make-semaphore :count 0)) 'nil)))
452
453 (with-test (:name (:try-semaphore :trivial-success))
454   (let ((sem (make-semaphore :count 1)))
455     (assert (try-semaphore sem))
456     (assert (zerop (semaphore-count sem)))))
457
458 (with-test (:name (:try-semaphore :trivial-fail :n>1))
459   (assert (eq (try-semaphore (make-semaphore :count 1) 2) 'nil)))
460
461 (with-test (:name (:try-semaphore :trivial-success :n>1))
462   (let ((sem (make-semaphore :count 10)))
463     (assert (try-semaphore sem 5))
464     (assert (try-semaphore sem 5))
465     (assert (zerop (semaphore-count sem)))))
466
467 (with-test (:name (:try-semaphore :emulate-wait-on-semaphore))
468   (flet ((busy-wait-on-semaphore (sem)
469            (loop until (try-semaphore sem) do (sleep 0.001))))
470     (test-semaphore-multiple-signals #'busy-wait-on-semaphore)))
471
472 ;;; Here we test that interrupting TRY-SEMAPHORE does not leave a
473 ;;; semaphore in a bad state.
474 (with-test (:name (:try-semaphore :interrupt-safe))
475   (flet ((make-threads (count fn)
476            (loop repeat count collect (make-thread fn)))
477          (kill-thread (thread)
478            (when (thread-alive-p thread)
479              (ignore-errors (terminate-thread thread))))
480          (count-live-threads (threads)
481            (count-if #'thread-alive-p threads)))
482     ;; WAITERS will already be waiting on the semaphore while
483     ;; threads-being-interrupted will perform TRY-SEMAPHORE on that
484     ;; semaphore, and MORE-WAITERS are new threads trying to wait on
485     ;; the semaphore during the interruption-fire.
486     (let* ((sem (make-semaphore :count 100))
487            (waiters (make-threads 20 #'(lambda ()
488                                          (wait-on-semaphore sem))))
489            (triers  (make-threads 40 #'(lambda ()
490                                          (sleep (random 0.01))
491                                          (try-semaphore sem (1+ (random 5))))))
492            (more-waiters
493             (loop repeat 10
494                   do (kill-thread (nth (random 40) triers))
495                   collect (make-thread #'(lambda () (wait-on-semaphore sem)))
496                   do (kill-thread (nth (random 40) triers)))))
497       (sleep 0.5)
498       ;; Now ensure that the waiting threads will all be waked up,
499       ;; i.e. that the semaphore is still working.
500       (loop repeat (+ (count-live-threads waiters)
501                       (count-live-threads more-waiters))
502             do (signal-semaphore sem))
503       (sleep 0.5)
504       (assert (zerop (count-live-threads triers)))
505       (assert (zerop (count-live-threads waiters)))
506       (assert (zerop (count-live-threads more-waiters))))))
507
508
509
510 (format t "~&semaphore tests done~%")
511
512 (defun test-interrupt (function-to-interrupt &optional quit-p)
513   (let ((child  (make-thread function-to-interrupt)))
514     ;;(format t "gdb ./src/runtime/sbcl ~A~%attach ~A~%" child child)
515     (sleep 2)
516     (format t "interrupting child ~A~%" child)
517     (interrupt-thread child
518                       (lambda ()
519                         (format t "child pid ~A~%" *current-thread*)
520                         (when quit-p (sb-ext:quit))))
521     (sleep 1)
522     child))
523
524 ;; separate tests for (a) interrupting Lisp code, (b) C code, (c) a syscall,
525 ;; (d) waiting on a lock, (e) some code which we hope is likely to be
526 ;; in pseudo-atomic
527
528 (with-test (:name (:interrupt-thread :more-basics))
529   (let ((child (test-interrupt (lambda () (loop)))))
530     (terminate-thread child)))
531
532 (with-test (:name (:interrupt-thread :interrupt-foreign-loop))
533   (test-interrupt #'loop-forever :quit))
534
535 (with-test (:name (:interrupt-thread :interrupt-sleep))
536   (let ((child (test-interrupt (lambda () (loop (sleep 2000))))))
537     (terminate-thread child)
538     (wait-for-threads (list child))))
539
540 (with-test (:name (:interrupt-thread :interrupt-mutex-acquisition))
541   (let ((lock (make-mutex :name "loctite"))
542         child)
543     (with-mutex (lock)
544       (setf child (test-interrupt
545                    (lambda ()
546                      (with-mutex (lock)
547                        (assert (eql (mutex-value lock) *current-thread*)))
548                      (assert (not (eql (mutex-value lock) *current-thread*)))
549                      (sleep 10))))
550       ;;hold onto lock for long enough that child can't get it immediately
551       (sleep 5)
552       (interrupt-thread child (lambda () (format t "l ~A~%" (mutex-value lock))))
553       (format t "parent releasing lock~%"))
554     (terminate-thread child)
555     (wait-for-threads (list child))))
556
557 (format t "~&locking test done~%")
558
559 (defun alloc-stuff () (copy-list '(1 2 3 4 5)))
560
561 (with-test (:name (:interrupt-thread :interrupt-consing-child))
562   (let ((thread (sb-thread:make-thread (lambda () (loop (alloc-stuff))))))
563     (let ((killers
564            (loop repeat 4 collect
565                  (sb-thread:make-thread
566                   (lambda ()
567                     (loop repeat 25 do
568                           (sleep (random 0.1d0))
569                           (princ ".")
570                           (force-output)
571                           (sb-thread:interrupt-thread thread (lambda ()))))))))
572       (wait-for-threads killers)
573       (sb-thread:terminate-thread thread)
574       (wait-for-threads (list thread))))
575   (sb-ext:gc :full t))
576
577 (format t "~&multi interrupt test done~%")
578
579 #+(or x86 x86-64) ;; x86oid-only, see internal commentary.
580 (with-test (:name (:interrupt-thread :interrupt-consing-child :again))
581   (let ((c (make-thread (lambda () (loop (alloc-stuff))))))
582     ;; NB this only works on x86: other ports don't have a symbol for
583     ;; pseudo-atomic atomicity
584     (dotimes (i 100)
585       (sleep (random 0.1d0))
586       (interrupt-thread c
587                         (lambda ()
588                           (princ ".") (force-output)
589                           (assert (thread-alive-p *current-thread*))
590                           (assert
591                            (not (logbitp 0 SB-KERNEL:*PSEUDO-ATOMIC-BITS*))))))
592     (terminate-thread c)
593     (wait-for-threads (list c))))
594
595 (format t "~&interrupt test done~%")
596
597 (defstruct counter (n 0 :type sb-vm:word))
598 (defvar *interrupt-counter* (make-counter))
599
600 (declaim (notinline check-interrupt-count))
601 (defun check-interrupt-count (i)
602   (declare (optimize (debug 1) (speed 1)))
603   ;; This used to lose if eflags were not restored after an interrupt.
604   (unless (typep i 'fixnum)
605     (error "!!!!!!!!!!!")))
606
607 (with-test (:name (:interrupt-thread :interrupt-ATOMIC-INCF))
608   (let ((c (make-thread
609             (lambda ()
610               (handler-bind ((error #'(lambda (cond)
611                                         (princ cond)
612                                         (sb-debug:backtrace
613                                          most-positive-fixnum))))
614                 (loop (check-interrupt-count
615                        (counter-n *interrupt-counter*))))))))
616     (let ((func (lambda ()
617                   (princ ".")
618                   (force-output)
619                   (sb-ext:atomic-incf (counter-n *interrupt-counter*)))))
620       (setf (counter-n *interrupt-counter*) 0)
621       (dotimes (i 100)
622         (sleep (random 0.1d0))
623         (interrupt-thread c func))
624       (loop until (= (counter-n *interrupt-counter*) 100) do (sleep 0.1))
625       (terminate-thread c)
626       (wait-for-threads (list c)))))
627
628 (format t "~&interrupt count test done~%")
629
630 (defvar *runningp* nil)
631
632 (with-test (:name (:interrupt-thread :no-nesting))
633   (let ((thread (sb-thread:make-thread
634                  (lambda ()
635                    (catch 'xxx
636                      (loop))))))
637     (declare (special runningp))
638     (sleep 0.2)
639     (sb-thread:interrupt-thread thread
640                                 (lambda ()
641                                     (let ((*runningp* t))
642                                       (sleep 1))))
643     (sleep 0.2)
644     (sb-thread:interrupt-thread thread
645                                 (lambda ()
646                                   (throw 'xxx *runningp*)))
647     (assert (not (sb-thread:join-thread thread)))))
648
649 (with-test (:name (:interrupt-thread :nesting))
650   (let ((thread (sb-thread:make-thread
651                  (lambda ()
652                    (catch 'xxx
653                      (loop))))))
654     (declare (special runningp))
655     (sleep 0.2)
656     (sb-thread:interrupt-thread thread
657                                 (lambda ()
658                                   (let ((*runningp* t))
659                                     (sb-sys:with-interrupts
660                                       (sleep 1)))))
661     (sleep 0.2)
662     (sb-thread:interrupt-thread thread
663                                 (lambda ()
664                                   (throw 'xxx *runningp*)))
665     (assert (sb-thread:join-thread thread))))
666
667 (with-test (:name (:two-threads-running-gc))
668   (let (a-done b-done)
669     (make-thread (lambda ()
670                    (dotimes (i 100)
671                      (sb-ext:gc) (princ "\\") (force-output))
672                    (setf a-done t)))
673     (make-thread (lambda ()
674                    (dotimes (i 25)
675                      (sb-ext:gc :full t)
676                      (princ "/") (force-output))
677                    (setf b-done t)))
678     (loop
679       (when (and a-done b-done) (return))
680       (sleep 1))))
681
682 (terpri)
683
684 (defun waste (&optional (n 100000))
685   (loop repeat n do (make-string 16384)))
686
687 (with-test (:name (:one-thread-runs-gc-while-other-conses))
688   (loop for i below 100 do
689         (princ "!")
690         (force-output)
691         (sb-thread:make-thread
692          #'(lambda ()
693              (waste)))
694         (waste)
695         (sb-ext:gc)))
696
697 (terpri)
698
699 (defparameter *aaa* nil)
700 (with-test (:name (:one-thread-runs-gc-while-other-conses :again))
701   (loop for i below 100 do
702         (princ "!")
703         (force-output)
704         (sb-thread:make-thread
705          #'(lambda ()
706              (let ((*aaa* (waste)))
707                (waste))))
708         (let ((*aaa* (waste)))
709           (waste))
710         (sb-ext:gc)))
711
712 (format t "~&gc test done~%")
713
714 ;; this used to deadlock on session-lock
715 (with-test (:name (:no-session-deadlock))
716   (sb-thread:make-thread (lambda () (sb-ext:gc))))
717
718 (defun exercise-syscall (fn reference-errno)
719   (sb-thread:make-thread
720    (lambda ()
721      (loop do
722           (funcall fn)
723           (let ((errno (sb-unix::get-errno)))
724             (sleep (random 0.1d0))
725             (unless (eql errno reference-errno)
726               (format t "Got errno: ~A (~A) instead of ~A~%"
727                       errno
728                       (sb-unix::strerror)
729                       reference-errno)
730               (force-output)
731               (sb-ext:quit :unix-status 1)))))))
732
733 ;; (nanosleep -1 0) does not fail on FreeBSD
734 (with-test (:name (:exercising-concurrent-syscalls))
735   (let* (#-freebsd
736          (nanosleep-errno (progn
737                             (sb-unix:nanosleep -1 0)
738                             (sb-unix::get-errno)))
739          (open-errno (progn
740                        (open "no-such-file"
741                              :if-does-not-exist nil)
742                        (sb-unix::get-errno)))
743          (threads
744           (list
745            #-freebsd
746            (exercise-syscall (lambda () (sb-unix:nanosleep -1 0)) nanosleep-errno)
747            (exercise-syscall (lambda () (open "no-such-file"
748                                               :if-does-not-exist nil))
749                              open-errno)
750            (sb-thread:make-thread (lambda () (loop (sb-ext:gc) (sleep 1)))))))
751     (sleep 10)
752     (princ "terminating threads")
753     (dolist (thread threads)
754       (sb-thread:terminate-thread thread))))
755
756 (format t "~&errno test done~%")
757
758 (with-test (:name (:terminate-thread-restart))
759   (loop repeat 100 do
760         (let ((thread (sb-thread:make-thread (lambda () (sleep 0.1)))))
761           (sb-thread:interrupt-thread
762            thread
763            (lambda ()
764              (assert (find-restart 'sb-thread:terminate-thread)))))))
765
766 (sb-ext:gc :full t)
767
768 (format t "~&thread startup sigmask test done~%")
769
770 (with-test (:name (:debugger-no-hang-on-session-lock-if-interrupted))
771   (sb-debug::enable-debugger)
772   (let* ((main-thread *current-thread*)
773          (interruptor-thread
774           (make-thread (lambda ()
775                          (sleep 2)
776                          (interrupt-thread main-thread
777                                            (lambda ()
778                                              (with-interrupts
779                                                (break))))
780                          (sleep 2)
781                          (interrupt-thread main-thread #'continue))
782                        :name "interruptor")))
783     (with-session-lock (*session*)
784       (sleep 3))
785     (loop while (thread-alive-p interruptor-thread))))
786
787 (format t "~&session lock test done~%")
788
789 ;; expose thread creation races by exiting quickly
790 (with-test (:name (:no-thread-creation-race :light))
791   (sb-thread:make-thread (lambda ())))
792
793 (with-test (:name (:no-thread-creation-race :heavy))
794   (loop repeat 20 do
795         (wait-for-threads
796          (loop for i below 100 collect
797                (sb-thread:make-thread (lambda ()))))))
798
799 (format t "~&creation test done~%")
800
801 ;; interrupt handlers are per-thread with pthreads, make sure the
802 ;; handler installed in one thread is global
803 (with-test (:name (:global-interrupt-handler))
804   (sb-thread:make-thread
805    (lambda ()
806      (sb-ext:run-program "sleep" '("1") :search t :wait nil))))
807
808 ;;;; Binding stack safety
809
810 (defparameter *x* nil)
811 (defparameter *n-gcs-requested* 0)
812 (defparameter *n-gcs-done* 0)
813
814 (let ((counter 0))
815   (defun make-something-big ()
816     (let ((x (make-string 32000)))
817       (incf counter)
818       (let ((counter counter))
819         (sb-ext:finalize x (lambda () (format t " ~S" counter)
820                                    (force-output)))))))
821
822 (defmacro wait-for-gc ()
823   `(progn
824      (incf *n-gcs-requested*)
825      (loop while (< *n-gcs-done* *n-gcs-requested*))))
826
827 (defun send-gc ()
828   (loop until (< *n-gcs-done* *n-gcs-requested*))
829   (format t "G")
830   (force-output)
831   (sb-ext:gc)
832   (incf *n-gcs-done*))
833
834 (defun exercise-binding ()
835   (loop
836    (let ((*x* (make-something-big)))
837      (let ((*x* 42))
838        ;; at this point the binding stack looks like this:
839        ;; NO-TLS-VALUE-MARKER, *x*, SOMETHING, *x*
840        t))
841    (wait-for-gc)
842    ;; sig_stop_for_gc_handler binds FREE_INTERRUPT_CONTEXT_INDEX. By
843    ;; now SOMETHING is gc'ed and the binding stack looks like this: 0,
844    ;; 0, SOMETHING, 0 (because the symbol slots are zeroed on
845    ;; unbinding but values are not).
846    (let ((*x* nil))
847      ;; bump bsp as if a BIND had just started
848      (incf sb-vm::*binding-stack-pointer* 2)
849      (wait-for-gc)
850      (decf sb-vm::*binding-stack-pointer* 2))))
851
852 (with-test (:name (:binding-stack-gc-safety))
853   (let (threads)
854     (unwind-protect
855          (progn
856            (push (sb-thread:make-thread #'exercise-binding) threads)
857            (push (sb-thread:make-thread (lambda ()
858                                           (loop
859                                            (sleep 0.1)
860                                            (send-gc))))
861                  threads)
862            (sleep 4))
863       (mapc #'sb-thread:terminate-thread threads))))
864
865 (format t "~&binding test done~%")
866
867 ;;; HASH TABLES
868
869 (defvar *errors* nil)
870
871 (defun oops (e)
872   (setf *errors* e)
873   (format t "~&oops: ~A in ~S~%" e *current-thread*)
874   (sb-debug:backtrace)
875   (catch 'done))
876
877 (with-test (:name (:unsynchronized-hash-table))
878   ;; We expect a (probable) error here: parellel readers and writers
879   ;; on a hash-table are not expected to work -- but we also don't
880   ;; expect this to corrupt the image.
881   (let* ((hash (make-hash-table))
882          (*errors* nil)
883          (threads (list (sb-thread:make-thread
884                          (lambda ()
885                            (catch 'done
886                              (handler-bind ((serious-condition 'oops))
887                                (loop
888                                  ;;(princ "1") (force-output)
889                                  (setf (gethash (random 100) hash) 'h)))))
890                          :name "writer")
891                         (sb-thread:make-thread
892                          (lambda ()
893                            (catch 'done
894                              (handler-bind ((serious-condition 'oops))
895                                (loop
896                                  ;;(princ "2") (force-output)
897                                  (remhash (random 100) hash)))))
898                          :name "reader")
899                         (sb-thread:make-thread
900                          (lambda ()
901                            (catch 'done
902                              (handler-bind ((serious-condition 'oops))
903                                (loop
904                                  (sleep (random 1.0))
905                                  (sb-ext:gc :full t)))))
906                          :name "collector"))))
907     (unwind-protect
908          (sleep 10)
909       (mapc #'sb-thread:terminate-thread threads))))
910
911 (format t "~&unsynchronized hash table test done~%")
912
913 (with-test (:name (:synchronized-hash-table))
914   (let* ((hash (make-hash-table :synchronized t))
915          (*errors* nil)
916          (threads (list (sb-thread:make-thread
917                          (lambda ()
918                            (catch 'done
919                              (handler-bind ((serious-condition 'oops))
920                                (loop
921                                  ;;(princ "1") (force-output)
922                                  (setf (gethash (random 100) hash) 'h)))))
923                          :name "writer")
924                         (sb-thread:make-thread
925                          (lambda ()
926                            (catch 'done
927                              (handler-bind ((serious-condition 'oops))
928                                (loop
929                                  ;;(princ "2") (force-output)
930                                  (remhash (random 100) hash)))))
931                          :name "reader")
932                         (sb-thread:make-thread
933                          (lambda ()
934                            (catch 'done
935                              (handler-bind ((serious-condition 'oops))
936                                (loop
937                                  (sleep (random 1.0))
938                                  (sb-ext:gc :full t)))))
939                          :name "collector"))))
940     (unwind-protect
941          (sleep 10)
942       (mapc #'sb-thread:terminate-thread threads))
943     (assert (not *errors*))))
944
945 (format t "~&synchronized hash table test done~%")
946
947 (with-test (:name (:hash-table-parallel-readers))
948   (let ((hash (make-hash-table))
949         (*errors* nil))
950     (loop repeat 50
951           do (setf (gethash (random 100) hash) 'xxx))
952     (let ((threads (list (sb-thread:make-thread
953                           (lambda ()
954                             (catch 'done
955                               (handler-bind ((serious-condition 'oops))
956                                 (loop
957                                       until (eq t (gethash (random 100) hash))))))
958                           :name "reader 1")
959                          (sb-thread:make-thread
960                           (lambda ()
961                             (catch 'done
962                               (handler-bind ((serious-condition 'oops))
963                                 (loop
964                                       until (eq t (gethash (random 100) hash))))))
965                           :name "reader 2")
966                          (sb-thread:make-thread
967                           (lambda ()
968                             (catch 'done
969                               (handler-bind ((serious-condition 'oops))
970                                 (loop
971                                       until (eq t (gethash (random 100) hash))))))
972                           :name "reader 3")
973                          (sb-thread:make-thread
974                           (lambda ()
975                             (catch 'done
976                               (handler-bind ((serious-condition 'oops))
977                                (loop
978                                  (sleep (random 1.0))
979                                  (sb-ext:gc :full t)))))
980                           :name "collector"))))
981       (unwind-protect
982            (sleep 10)
983         (mapc #'sb-thread:terminate-thread threads))
984       (assert (not *errors*)))))
985
986 (format t "~&multiple reader hash table test done~%")
987
988 (with-test (:name (:hash-table-single-accessor-parallel-gc))
989   (let ((hash (make-hash-table))
990         (*errors* nil))
991     (let ((threads (list (sb-thread:make-thread
992                           (lambda ()
993                             (handler-bind ((serious-condition 'oops))
994                               (loop
995                                 (let ((n (random 100)))
996                                   (if (gethash n hash)
997                                       (remhash n hash)
998                                       (setf (gethash n hash) 'h))))))
999                           :name "accessor")
1000                          (sb-thread:make-thread
1001                           (lambda ()
1002                             (handler-bind ((serious-condition 'oops))
1003                               (loop
1004                                 (sleep (random 1.0))
1005                                 (sb-ext:gc :full t))))
1006                           :name "collector"))))
1007       (unwind-protect
1008            (sleep 10)
1009         (mapc #'sb-thread:terminate-thread threads))
1010       (assert (not *errors*)))))
1011
1012 (format t "~&single accessor hash table test~%")
1013
1014 #|  ;; a cll post from eric marsden
1015 | (defun crash ()
1016 |   (setq *debugger-hook*
1017 |         (lambda (condition old-debugger-hook)
1018 |           (debug:backtrace 10)
1019 |           (unix:unix-exit 2)))
1020 |   #+live-dangerously
1021 |   (mp::start-sigalrm-yield)
1022 |   (flet ((roomy () (loop (with-output-to-string (*standard-output*) (room)))))
1023 |     (mp:make-process #'roomy)
1024 |     (mp:make-process #'roomy)))
1025 |#
1026
1027 (with-test (:name (:condition-variable :notify-multiple))
1028   (flet ((tester (notify-fun)
1029            (let ((queue (make-waitqueue :name "queue"))
1030                  (lock (make-mutex :name "lock"))
1031                  (data nil))
1032              (labels ((test (x)
1033                         (loop
1034                            (with-mutex (lock)
1035                              (format t "condition-wait ~a~%" x)
1036                              (force-output)
1037                              (condition-wait queue lock)
1038                              (format t "woke up ~a~%" x)
1039                              (force-output)
1040                              (push x data)))))
1041                (let ((threads (loop for x from 1 to 10
1042                                     collect
1043                                     (let ((x x))
1044                                       (sb-thread:make-thread (lambda ()
1045                                                                (test x)))))))
1046                  (sleep 5)
1047                  (with-mutex (lock)
1048                    (funcall notify-fun queue))
1049                  (sleep 5)
1050                  (mapcar #'terminate-thread threads)
1051                  ;; Check that all threads woke up at least once
1052                  (assert (= (length (remove-duplicates data)) 10)))))))
1053     (tester (lambda (queue)
1054               (format t "~&(condition-notify queue 10)~%")
1055               (force-output)
1056               (condition-notify queue 10)))
1057     (tester (lambda (queue)
1058               (format t "~&(condition-broadcast queue)~%")
1059               (force-output)
1060               (condition-broadcast queue)))))
1061
1062 (format t "waitqueue wakeup tests done~%")
1063
1064 ;;; Make sure that a deadline handler is not invoked twice in a row in
1065 ;;; CONDITION-WAIT. See LP #512914 for a detailed explanation.
1066 ;;;
1067 #-sb-lutex    ; See KLUDGE above: no deadlines for condition-wait+lutexes.
1068 (with-test (:name (:condition-wait :deadlines :LP-512914))
1069   (let ((n 2) ; was empirically enough to trigger the bug
1070         (mutex (sb-thread:make-mutex))
1071         (waitq (sb-thread:make-waitqueue))
1072         (threads nil)
1073         (deadline-handler-run-twice? nil))
1074     (dotimes (i n)
1075       (let ((child
1076              (sb-thread:make-thread
1077               #'(lambda ()
1078                   (handler-bind
1079                       ((sb-sys:deadline-timeout
1080                         (let ((already? nil))
1081                           #'(lambda (c)
1082                               (when already?
1083                                 (setq deadline-handler-run-twice? t))
1084                               (setq already? t)
1085                               (sleep 0.2)
1086                               (sb-thread:condition-broadcast waitq)
1087                               (sb-sys:defer-deadline 10.0 c)))))
1088                     (sb-sys:with-deadline (:seconds 0.1)
1089                       (sb-thread:with-mutex (mutex)
1090                         (sb-thread:condition-wait waitq mutex))))))))
1091         (push child threads)))
1092     (mapc #'sb-thread:join-thread threads)
1093     (assert (not deadline-handler-run-twice?))))
1094
1095 (with-test (:name (:condition-wait :signal-deadline-with-interrupts-enabled))
1096   #+darwin
1097   (error "Bad Darwin")
1098   (let ((mutex (sb-thread:make-mutex))
1099         (waitq (sb-thread:make-waitqueue))
1100         (A-holds? :unknown)
1101         (B-holds? :unknown)
1102         (A-interrupts-enabled? :unknown)
1103         (B-interrupts-enabled? :unknown)
1104         (A)
1105         (B))
1106     ;; W.L.O.G., we assume that A is executed first...
1107     (setq A (sb-thread:make-thread
1108              #'(lambda ()
1109                  (handler-bind
1110                      ((sb-sys:deadline-timeout
1111                        #'(lambda (c)
1112                            ;; We came here through the call to DECODE-TIMEOUT
1113                            ;; in CONDITION-WAIT; hence both here are supposed
1114                            ;; to evaluate to T.
1115                            (setq A-holds? (sb-thread:holding-mutex-p mutex))
1116                            (setq A-interrupts-enabled?
1117                                  sb-sys:*interrupts-enabled*)
1118                            (sleep 0.2)
1119                            (sb-thread:condition-broadcast waitq)
1120                            (sb-sys:defer-deadline 10.0 c))))
1121                    (sb-sys:with-deadline (:seconds 0.1)
1122                      (sb-thread:with-mutex (mutex)
1123                        (sb-thread:condition-wait waitq mutex)))))))
1124     (setq B (sb-thread:make-thread
1125              #'(lambda ()
1126                  (thread-yield)
1127                  (handler-bind
1128                      ((sb-sys:deadline-timeout
1129                        #'(lambda (c)
1130                            ;; We came here through the call to GET-MUTEX
1131                            ;; in CONDITION-WAIT (contended case of
1132                            ;; reaquiring the mutex) - so the former will
1133                            ;; be NIL, but interrupts should still be enabled.
1134                            (setq B-holds? (sb-thread:holding-mutex-p mutex))
1135                            (setq B-interrupts-enabled?
1136                                  sb-sys:*interrupts-enabled*)
1137                            (sleep 0.2)
1138                            (sb-thread:condition-broadcast waitq)
1139                            (sb-sys:defer-deadline 10.0 c))))
1140                    (sb-sys:with-deadline (:seconds 0.1)
1141                      (sb-thread:with-mutex (mutex)
1142                        (sb-thread:condition-wait waitq mutex)))))))
1143     (sb-thread:join-thread A)
1144     (sb-thread:join-thread B)
1145     (let ((A-result (list A-holds? A-interrupts-enabled?))
1146           (B-result (list B-holds? B-interrupts-enabled?)))
1147       ;; We also check some subtle behaviour w.r.t. whether a deadline
1148       ;; handler in CONDITION-WAIT got the mutex, or not. This is most
1149       ;; probably very internal behaviour (so user should not depend
1150       ;; on it) -- I added the testing here just to manifest current
1151       ;; behaviour.
1152       (cond ((equal A-result '(t t)) (assert (equal B-result '(nil t))))
1153             ((equal B-result '(t t)) (assert (equal A-result '(nil t))))
1154             (t (error "Failure: fall through."))))))
1155
1156 (with-test (:name (:mutex :finalization))
1157   (let ((a nil))
1158     (dotimes (i 500000)
1159       (setf a (make-mutex)))))
1160
1161 (format t "mutex finalization test done~%")
1162
1163 ;;; Check that INFO is thread-safe, at least when we're just doing reads.
1164
1165 (let* ((symbols (loop repeat 10000 collect (gensym)))
1166        (functions (loop for (symbol . rest) on symbols
1167                         for next = (car rest)
1168                         for fun = (let ((next next))
1169                                     (lambda (n)
1170                                       (if next
1171                                           (funcall next (1- n))
1172                                           n)))
1173                         do (setf (symbol-function symbol) fun)
1174                         collect fun)))
1175   (defun infodb-test ()
1176     (funcall (car functions) 9999)))
1177
1178 (with-test (:name (:infodb :read))
1179   (let* ((ok t)
1180          (threads (loop for i from 0 to 10
1181                         collect (sb-thread:make-thread
1182                                  (lambda ()
1183                                    (dotimes (j 100)
1184                                      (write-char #\-)
1185                                      (finish-output)
1186                                      (let ((n (infodb-test)))
1187                                        (unless (zerop n)
1188                                          (setf ok nil)
1189                                          (format t "N != 0 (~A)~%" n)
1190                                          (sb-ext:quit)))))))))
1191     (wait-for-threads threads)
1192     (assert ok)))
1193
1194 (format t "infodb test done~%")
1195
1196 (with-test (:name (:backtrace))
1197   #+darwin
1198   (error "Prone to crash on Darwin, cause unknown.")
1199   ;; Printing backtraces from several threads at once used to hang the
1200   ;; whole SBCL process (discovered by accident due to a timer.impure
1201   ;; test misbehaving). The cause was that packages weren't even
1202   ;; thread-safe for only doing FIND-SYMBOL, and while printing
1203   ;; backtraces a loot of symbol lookups need to be done due to
1204   ;; *PRINT-ESCAPE*.
1205   (let* ((threads (loop repeat 10
1206                         collect (sb-thread:make-thread
1207                                  (lambda ()
1208                                    (dotimes (i 1000)
1209                                      (with-output-to-string (*debug-io*)
1210                                        (sb-debug::backtrace 10))))))))
1211     (wait-for-threads threads)))
1212
1213 (format t "backtrace test done~%")
1214
1215 (format t "~&starting gc deadlock test: WARNING: THIS TEST WILL HANG ON FAILURE!~%")
1216
1217 (with-test (:name (:gc-deadlock))
1218   #+darwin
1219   (error "Prone to hang on Darwin due to interrupt issues.")
1220   ;; Prior to 0.9.16.46 thread exit potentially deadlocked the
1221   ;; GC due to *all-threads-lock* and session lock. On earlier
1222   ;; versions and at least on one specific box this test is good enough
1223   ;; to catch that typically well before the 1500th iteration.
1224   (loop
1225      with i = 0
1226      with n = 3000
1227      while (< i n)
1228      do
1229        (incf i)
1230        (when (zerop (mod i 100))
1231          (write-char #\.)
1232          (force-output))
1233        (handler-case
1234            (if (oddp i)
1235                (sb-thread:make-thread
1236                 (lambda ()
1237                   (sleep (random 0.001)))
1238                 :name (format nil "SLEEP-~D" i))
1239                (sb-thread:make-thread
1240                 (lambda ()
1241                   ;; KLUDGE: what we are doing here is explicit,
1242                   ;; but the same can happen because of a regular
1243                   ;; MAKE-THREAD or LIST-ALL-THREADS, and various
1244                   ;; session functions.
1245                   (sb-thread::with-all-threads-lock
1246                     (sb-thread::with-session-lock (sb-thread::*session*)
1247                       (sb-ext:gc))))
1248                 :name (format nil "GC-~D" i)))
1249          (error (e)
1250            (format t "~%error creating thread ~D: ~A -- backing off for retry~%" i e)
1251            (sleep 0.1)
1252            (incf i)))))
1253
1254 (format t "~&gc deadlock test done~%")
1255 \f
1256 (let ((count (make-array 8 :initial-element 0)))
1257   (defun closure-one ()
1258     (declare (optimize safety))
1259     (values (incf (aref count 0)) (incf (aref count 1))
1260             (incf (aref count 2)) (incf (aref count 3))
1261             (incf (aref count 4)) (incf (aref count 5))
1262             (incf (aref count 6)) (incf (aref count 7))))
1263   (defun no-optimizing-away-closure-one ()
1264     (setf count (make-array 8 :initial-element 0))))
1265
1266 (defstruct box
1267   (count 0))
1268
1269 (let ((one (make-box))
1270       (two (make-box))
1271       (three (make-box)))
1272   (defun closure-two ()
1273     (declare (optimize safety))
1274     (values (incf (box-count one)) (incf (box-count two)) (incf (box-count three))))
1275   (defun no-optimizing-away-closure-two ()
1276     (setf one (make-box)
1277           two (make-box)
1278           three (make-box))))
1279
1280 (with-test (:name (:funcallable-instances))
1281   ;; the funcallable-instance implementation used not to be threadsafe
1282   ;; against setting the funcallable-instance function to a closure
1283   ;; (because the code and lexenv were set separately).
1284   (let ((fun (sb-kernel:%make-funcallable-instance 0))
1285         (condition nil))
1286     (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
1287     (flet ((changer ()
1288              (loop (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
1289                    (setf (sb-kernel:funcallable-instance-fun fun) #'closure-two)))
1290            (test ()
1291              (handler-case (loop (funcall fun))
1292                (serious-condition (c) (setf condition c)))))
1293       (let ((changer (make-thread #'changer))
1294             (test (make-thread #'test)))
1295         (handler-case
1296             (progn
1297               ;; The two closures above are fairly carefully crafted
1298               ;; so that if given the wrong lexenv they will tend to
1299               ;; do some serious damage, but it is of course difficult
1300               ;; to predict where the various bits and pieces will be
1301               ;; allocated.  Five seconds failed fairly reliably on
1302               ;; both my x86 and x86-64 systems.  -- CSR, 2006-09-27.
1303               (sb-ext:with-timeout 5
1304                 (wait-for-threads (list test)))
1305               (error "~@<test thread got condition:~2I~_~A~@:>" condition))
1306           (sb-ext:timeout ()
1307             (terminate-thread changer)
1308             (terminate-thread test)
1309             (wait-for-threads (list changer test))))))))
1310
1311 (format t "~&funcallable-instance test done~%")
1312
1313 (defun random-type (n)
1314   `(integer ,(random n) ,(+ n (random n))))
1315
1316 (defun subtypep-hash-cache-test ()
1317   (dotimes (i 10000)
1318     (let ((type1 (random-type 500))
1319           (type2 (random-type 500)))
1320       (let ((a (subtypep type1 type2)))
1321         (dotimes (i 100)
1322           (assert (eq (subtypep type1 type2) a))))))
1323   (format t "ok~%")
1324   (force-output))
1325
1326 (with-test (:name (:hash-cache :subtypep))
1327   (dotimes (i 10)
1328     (sb-thread:make-thread #'subtypep-hash-cache-test)))
1329 (format t "hash-cache tests done~%")
1330
1331 ;;;; BLACK BOX TESTS
1332
1333 (in-package :cl-user)
1334 (use-package :test-util)
1335 (use-package "ASSERTOID")
1336
1337 (format t "parallel defclass test -- WARNING, WILL HANG ON FAILURE!~%")
1338 (with-test (:name :parallel-defclass)
1339   (defclass test-1 () ((a :initform :orig-a)))
1340   (defclass test-2 () ((b :initform :orig-b)))
1341   (defclass test-3 (test-1 test-2) ((c :initform :orig-c)))
1342   (let* ((run t)
1343          (d1 (sb-thread:make-thread (lambda ()
1344                                       (loop while run
1345                                             do (defclass test-1 () ((a :initform :new-a)))
1346                                             (write-char #\1)
1347                                             (force-output)))
1348                                     :name "d1"))
1349          (d2 (sb-thread:make-thread (lambda ()
1350                                       (loop while run
1351                                             do (defclass test-2 () ((b :initform :new-b)))
1352                                                (write-char #\2)
1353                                                (force-output)))
1354                                     :name "d2"))
1355          (d3 (sb-thread:make-thread (lambda ()
1356                                       (loop while run
1357                                             do (defclass test-3 (test-1 test-2) ((c :initform :new-c)))
1358                                                (write-char #\3)
1359                                                (force-output)))
1360                                     :name "d3"))
1361          (i (sb-thread:make-thread (lambda ()
1362                                      (loop while run
1363                                            do (let ((i (make-instance 'test-3)))
1364                                                 (assert (member (slot-value i 'a) '(:orig-a :new-a)))
1365                                                 (assert (member (slot-value i 'b) '(:orig-b :new-b)))
1366                                                 (assert (member (slot-value i 'c) '(:orig-c :new-c))))
1367                                               (write-char #\i)
1368                                               (force-output)))
1369                                    :name "i")))
1370     (format t "~%sleeping!~%")
1371     (sleep 2.0)
1372     (format t "~%stopping!~%")
1373     (setf run nil)
1374     (mapc (lambda (th)
1375             (sb-thread:join-thread th)
1376             (format t "~%joined ~S~%" (sb-thread:thread-name th)))
1377           (list d1 d2 d3 i))))
1378 (format t "parallel defclass test done~%")