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