1.0.4.4: simplify JOIN-THREAD interface
[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 (in-package "SB-THREAD") ; this is white-box testing, really
15
16 (use-package :test-util)
17 (use-package "ASSERTOID")
18
19 (defun wait-for-threads (threads)
20   (mapc (lambda (thread) (sb-thread:join-thread thread :default nil)) threads)
21   (assert (not (some #'sb-thread:thread-alive-p threads))))
22
23 (assert (eql 1 (length (list-all-threads))))
24
25 (assert (eq *current-thread*
26             (find (thread-name *current-thread*) (list-all-threads)
27                   :key #'thread-name :test #'equal)))
28
29 (assert (thread-alive-p *current-thread*))
30
31 (let ((a 0))
32   (interrupt-thread *current-thread* (lambda () (setq a 1)))
33   (assert (eql a 1)))
34
35 (let ((spinlock (make-spinlock)))
36   (with-spinlock (spinlock)))
37
38 (let ((mutex (make-mutex)))
39   (with-mutex (mutex)
40     mutex))
41
42 #-sb-thread (sb-ext:quit :unix-status 104)
43
44 (let ((old-threads (list-all-threads))
45       (thread (make-thread (lambda ()
46                              (assert (find *current-thread* *all-threads*))
47                              (sleep 2))))
48       (new-threads (list-all-threads)))
49   (assert (thread-alive-p thread))
50   (assert (eq thread (first new-threads)))
51   (assert (= (1+ (length old-threads)) (length new-threads)))
52   (sleep 3)
53   (assert (not (thread-alive-p thread))))
54
55 (with-test (:name '(:join-thread :nlx :default))
56   (let ((sym (gensym)))
57     (assert (eq sym (join-thread (make-thread (lambda () (sb-ext:quit)))
58                                  :default sym)))))
59
60 (with-test (:name '(:join-thread :nlx :error))
61   (raises-error? (join-thread (make-thread (lambda () (sb-ext:quit))))))
62
63 (with-test (:name '(:join-thread :multiple-values))
64   (assert (equal '(1 2 3)
65                  (multiple-value-list
66                   (join-thread (make-thread (lambda () (values 1 2 3))))))))
67
68 ;;; We had appalling scaling properties for a while.  Make sure they
69 ;;; don't reappear.
70 (defun scaling-test (function &optional (nthreads 5))
71   "Execute FUNCTION with NTHREADS lurking to slow it down."
72   (let ((queue (sb-thread:make-waitqueue))
73         (mutex (sb-thread:make-mutex)))
74     ;; Start NTHREADS idle threads.
75     (dotimes (i nthreads)
76       (sb-thread:make-thread (lambda ()
77                                (with-mutex (mutex)
78                                  (sb-thread:condition-wait queue mutex))
79                                (sb-ext:quit))))
80     (let ((start-time (get-internal-run-time)))
81       (funcall function)
82       (prog1 (- (get-internal-run-time) start-time)
83         (sb-thread:condition-broadcast queue)))))
84 (defun fact (n)
85   "A function that does work with the CPU."
86   (if (zerop n) 1 (* n (fact (1- n)))))
87 (let ((work (lambda () (fact 15000))))
88   (let ((zero (scaling-test work 0))
89         (four (scaling-test work 4)))
90     ;; a slightly weak assertion, but good enough for starters.
91     (assert (< four (* 1.5 zero)))))
92
93 ;;; For one of the interupt-thread tests, we want a foreign function
94 ;;; that does not make syscalls
95
96 (with-open-file (o "threads-foreign.c" :direction :output :if-exists :supersede)
97   (format o "void loop_forever() { while(1) ; }~%"))
98 (sb-ext:run-program
99  #-sunos "cc" #+sunos "gcc"
100  (or #+(or linux freebsd sunos) '(#+x86-64 "-fPIC"
101                                   "-shared" "-o" "threads-foreign.so" "threads-foreign.c")
102      #+darwin '("-dynamiclib" "-o" "threads-foreign.so" "threads-foreign.c")
103      (error "Missing shared library compilation options for this platform"))
104  :search t)
105 (sb-alien:load-shared-object "threads-foreign.so")
106 (sb-alien:define-alien-routine loop-forever sb-alien:void)
107
108
109 ;;; elementary "can we get a lock and release it again"
110 (let ((l (make-mutex :name "foo"))
111       (p *current-thread*))
112   (assert (eql (mutex-value l) nil) nil "1")
113   (sb-thread:get-mutex l)
114   (assert (eql (mutex-value l) p) nil "3")
115   (sb-thread:release-mutex l)
116   (assert (eql (mutex-value l) nil) nil "5"))
117
118 (labels ((ours-p (value)
119            (eq *current-thread* value)))
120   (let ((l (make-mutex :name "rec")))
121     (assert (eql (mutex-value l) nil) nil "1")
122     (sb-thread:with-recursive-lock (l)
123       (assert (ours-p (mutex-value l)) nil "3")
124       (sb-thread:with-recursive-lock (l)
125         (assert (ours-p (mutex-value l)) nil "4"))
126       (assert (ours-p (mutex-value l)) nil "5"))
127     (assert (eql (mutex-value l) nil) nil "6")))
128
129 (with-test (:name (:mutex :nesting-mutex-and-recursive-lock))
130   (let ((l (make-mutex :name "a mutex")))
131     (with-mutex (l)
132       (with-recursive-lock (l)))))
133
134 (let ((l (make-spinlock :name "spinlock")))
135   (assert (eql (spinlock-value l) 0) nil "1")
136   (with-spinlock (l)
137     (assert (eql (spinlock-value l) 1) nil "2"))
138   (assert (eql (spinlock-value l) 0) nil "3"))
139
140 ;; test that SLEEP actually sleeps for at least the given time, even
141 ;; if interrupted by another thread exiting/a gc/anything
142 (let ((start-time (get-universal-time)))
143   (make-thread (lambda () (sleep 1) (sb-ext:gc :full t)))
144   (sleep 5)
145   (assert (>= (get-universal-time) (+ 5 start-time))))
146
147
148 (let ((queue (make-waitqueue :name "queue"))
149       (lock (make-mutex :name "lock"))
150       (n 0))
151   (labels ((in-new-thread ()
152              (with-mutex (lock)
153                (assert (eql (mutex-value lock) *current-thread*))
154                (format t "~A got mutex~%" *current-thread*)
155                ;; now drop it and sleep
156                (condition-wait queue lock)
157                ;; after waking we should have the lock again
158                (assert (eql (mutex-value lock) *current-thread*))
159                (assert (eql n 1))
160                (decf n))))
161     (make-thread #'in-new-thread)
162     (sleep 2)                           ; give it  a chance to start
163     ;; check the lock is free while it's asleep
164     (format t "parent thread ~A~%" *current-thread*)
165     (assert (eql (mutex-value lock) nil))
166     (with-mutex (lock)
167       (incf n)
168       (condition-notify queue))
169     (sleep 1)))
170
171 (let ((queue (make-waitqueue :name "queue"))
172       (lock (make-mutex :name "lock")))
173   (labels ((ours-p (value)
174              (eq *current-thread* value))
175            (in-new-thread ()
176              (with-recursive-lock (lock)
177                (assert (ours-p (mutex-value lock)))
178                (format t "~A got mutex~%" (mutex-value lock))
179                ;; now drop it and sleep
180                (condition-wait queue lock)
181                ;; after waking we should have the lock again
182                (format t "woken, ~A got mutex~%" (mutex-value lock))
183                (assert (ours-p (mutex-value lock))))))
184     (make-thread #'in-new-thread)
185     (sleep 2)                           ; give it  a chance to start
186     ;; check the lock is free while it's asleep
187     (format t "parent thread ~A~%" *current-thread*)
188     (assert (eql (mutex-value lock) nil))
189     (with-recursive-lock (lock)
190       (condition-notify queue))
191     (sleep 1)))
192
193 (let ((mutex (make-mutex :name "contended")))
194   (labels ((run ()
195              (let ((me *current-thread*))
196                (dotimes (i 100)
197                  (with-mutex (mutex)
198                    (sleep .03)
199                    (assert (eql (mutex-value mutex) me)))
200                  (assert (not (eql (mutex-value mutex) me))))
201                (format t "done ~A~%" *current-thread*))))
202     (let ((kid1 (make-thread #'run))
203           (kid2 (make-thread #'run)))
204       (format t "contention ~A ~A~%" kid1 kid2)
205       (wait-for-threads (list kid1 kid2)))))
206
207 ;;; semaphores
208
209 (defmacro raises-timeout-p (&body body)
210   `(handler-case (progn (progn ,@body) nil)
211     (sb-ext:timeout () t)))
212
213 (with-test (:name (:semaphore :wait-forever))
214   (let ((sem (make-semaphore :count 0)))
215     (assert (raises-timeout-p
216               (sb-ext:with-timeout 0.1
217                 (wait-on-semaphore sem))))))
218
219 (with-test (:name (:semaphore :initial-count))
220   (let ((sem (make-semaphore :count 1)))
221     (sb-ext:with-timeout 0.1
222       (wait-on-semaphore sem))))
223
224 (with-test (:name (:semaphore :wait-then-signal))
225   (let ((sem (make-semaphore))
226         (signalled-p nil))
227     (make-thread (lambda ()
228                    (sleep 0.1)
229                    (setq signalled-p t)
230                    (signal-semaphore sem)))
231     (wait-on-semaphore sem)
232     (assert signalled-p)))
233
234 (with-test (:name (:semaphore :signal-then-wait))
235   (let ((sem (make-semaphore))
236         (signalled-p nil))
237     (make-thread (lambda ()
238                    (signal-semaphore sem)
239                    (setq signalled-p t)))
240     (loop until signalled-p)
241     (wait-on-semaphore sem)
242     (assert signalled-p)))
243
244 (with-test (:name (:semaphore :multiple-signals))
245   (let* ((sem (make-semaphore :count 5))
246          (threads (loop repeat 20
247                         collect (make-thread (lambda ()
248                                                (wait-on-semaphore sem))))))
249     (flet ((count-live-threads ()
250              (count-if #'thread-alive-p threads)))
251       (sleep 0.5)
252       (assert (= 15 (count-live-threads)))
253       (signal-semaphore sem 10)
254       (sleep 0.5)
255       (assert (= 5 (count-live-threads)))
256       (signal-semaphore sem 3)
257       (sleep 0.5)
258       (assert (= 2 (count-live-threads)))
259       (signal-semaphore sem 4)
260       (sleep 0.5)
261       (assert (= 0 (count-live-threads))))))
262
263 (format t "~&semaphore tests done~%")
264
265 (defun test-interrupt (function-to-interrupt &optional quit-p)
266   (let ((child  (make-thread function-to-interrupt)))
267     ;;(format t "gdb ./src/runtime/sbcl ~A~%attach ~A~%" child child)
268     (sleep 2)
269     (format t "interrupting child ~A~%" child)
270     (interrupt-thread child
271                       (lambda ()
272                         (format t "child pid ~A~%" *current-thread*)
273                         (when quit-p (sb-ext:quit))))
274     (sleep 1)
275     child))
276
277 ;; separate tests for (a) interrupting Lisp code, (b) C code, (c) a syscall,
278 ;; (d) waiting on a lock, (e) some code which we hope is likely to be
279 ;; in pseudo-atomic
280
281 (let ((child (test-interrupt (lambda () (loop)))))  (terminate-thread child))
282
283 (test-interrupt #'loop-forever :quit)
284
285 (let ((child (test-interrupt (lambda () (loop (sleep 2000))))))
286   (terminate-thread child)
287   (wait-for-threads (list child)))
288
289 (let ((lock (make-mutex :name "loctite"))
290       child)
291   (with-mutex (lock)
292     (setf child (test-interrupt
293                  (lambda ()
294                    (with-mutex (lock)
295                      (assert (eql (mutex-value lock) *current-thread*)))
296                    (assert (not (eql (mutex-value lock) *current-thread*)))
297                    (sleep 10))))
298     ;;hold onto lock for long enough that child can't get it immediately
299     (sleep 5)
300     (interrupt-thread child (lambda () (format t "l ~A~%" (mutex-value lock))))
301     (format t "parent releasing lock~%"))
302   (terminate-thread child)
303   (wait-for-threads (list child)))
304
305 (format t "~&locking test done~%")
306
307 (defun alloc-stuff () (copy-list '(1 2 3 4 5)))
308
309 (progn
310   (let ((thread (sb-thread:make-thread (lambda () (loop (alloc-stuff))))))
311     (let ((killers
312            (loop repeat 4 collect
313                  (sb-thread:make-thread
314                   (lambda ()
315                     (loop repeat 25 do
316                           (sleep (random 0.1d0))
317                           (princ ".")
318                           (force-output)
319                           (sb-thread:interrupt-thread thread (lambda ()))))))))
320       (wait-for-threads killers)
321       (sb-thread:terminate-thread thread)
322       (wait-for-threads (list thread))))
323   (sb-ext:gc :full t))
324
325 (format t "~&multi interrupt test done~%")
326
327 (let ((c (make-thread (lambda () (loop (alloc-stuff))))))
328   ;; NB this only works on x86: other ports don't have a symbol for
329   ;; pseudo-atomic atomicity
330   (dotimes (i 100)
331     (sleep (random 0.1d0))
332     (interrupt-thread c
333                       (lambda ()
334                         (princ ".") (force-output)
335                         (assert (thread-alive-p *current-thread*))
336                         (assert
337                          (not (logbitp 0 SB-KERNEL:*PSEUDO-ATOMIC-BITS*))))))
338   (terminate-thread c)
339   (wait-for-threads (list c)))
340
341 (format t "~&interrupt test done~%")
342
343 (defparameter *interrupt-count* 0)
344
345 (declaim (notinline check-interrupt-count))
346 (defun check-interrupt-count (i)
347   (declare (optimize (debug 1) (speed 1)))
348   ;; This used to lose if eflags were not restored after an interrupt.
349   (unless (typep i 'fixnum)
350     (error "!!!!!!!!!!!")))
351
352 (let ((c (make-thread
353           (lambda ()
354             (handler-bind ((error #'(lambda (cond)
355                                       (princ cond)
356                                       (sb-debug:backtrace
357                                        most-positive-fixnum))))
358               (loop (check-interrupt-count *interrupt-count*)))))))
359   (let ((func (lambda ()
360                 (princ ".")
361                 (force-output)
362                 (sb-impl::atomic-incf/symbol *interrupt-count*))))
363     (setq *interrupt-count* 0)
364     (dotimes (i 100)
365       (sleep (random 0.1d0))
366       (interrupt-thread c func))
367     (loop until (= *interrupt-count* 100) do (sleep 0.1))
368     (terminate-thread c)
369     (wait-for-threads (list c))))
370
371 (format t "~&interrupt count test done~%")
372
373 (let (a-done b-done)
374   (make-thread (lambda ()
375                  (dotimes (i 100)
376                    (sb-ext:gc) (princ "\\") (force-output))
377                  (setf a-done t)))
378   (make-thread (lambda ()
379                  (dotimes (i 25)
380                    (sb-ext:gc :full t)
381                    (princ "/") (force-output))
382                  (setf b-done t)))
383   (loop
384    (when (and a-done b-done) (return))
385    (sleep 1)))
386
387 (terpri)
388
389 (defun waste (&optional (n 100000))
390   (loop repeat n do (make-string 16384)))
391
392 (loop for i below 100 do
393       (princ "!")
394       (force-output)
395       (sb-thread:make-thread
396        #'(lambda ()
397            (waste)))
398       (waste)
399       (sb-ext:gc))
400
401 (terpri)
402
403 (defparameter *aaa* nil)
404 (loop for i below 100 do
405       (princ "!")
406       (force-output)
407       (sb-thread:make-thread
408        #'(lambda ()
409            (let ((*aaa* (waste)))
410              (waste))))
411       (let ((*aaa* (waste)))
412         (waste))
413       (sb-ext:gc))
414
415 (format t "~&gc test done~%")
416
417 ;; this used to deadlock on session-lock
418 (sb-thread:make-thread (lambda () (sb-ext:gc)))
419 ;; expose thread creation races by exiting quickly
420 (sb-thread:make-thread (lambda ()))
421
422 (defun exercise-syscall (fn reference-errno)
423   (sb-thread:make-thread
424    (lambda ()
425      (loop do
426           (funcall fn)
427           (let ((errno (sb-unix::get-errno)))
428             (sleep (random 0.1d0))
429             (unless (eql errno reference-errno)
430               (format t "Got errno: ~A (~A) instead of ~A~%"
431                       errno
432                       (sb-unix::strerror)
433                       reference-errno)
434               (force-output)
435               (sb-ext:quit :unix-status 1)))))))
436
437 ;; (nanosleep -1 0) does not fail on FreeBSD
438 (let* (#-freebsd
439        (nanosleep-errno (progn
440                           (sb-unix:nanosleep -1 0)
441                           (sb-unix::get-errno)))
442        (open-errno (progn
443                      (open "no-such-file"
444                            :if-does-not-exist nil)
445                      (sb-unix::get-errno)))
446        (threads
447         (list
448          #-freebsd
449          (exercise-syscall (lambda () (sb-unix:nanosleep -1 0)) nanosleep-errno)
450          (exercise-syscall (lambda () (open "no-such-file"
451                                             :if-does-not-exist nil))
452                            open-errno)
453          (sb-thread:make-thread (lambda () (loop (sb-ext:gc) (sleep 1)))))))
454   (sleep 10)
455   (princ "terminating threads")
456   (dolist (thread threads)
457     (sb-thread:terminate-thread thread)))
458
459 (format t "~&errno test done~%")
460
461 (loop repeat 100 do
462       (let ((thread (sb-thread:make-thread (lambda () (sleep 0.1)))))
463         (sb-thread:interrupt-thread
464          thread
465          (lambda ()
466            (assert (find-restart 'sb-thread:terminate-thread))))))
467
468 (sb-ext:gc :full t)
469
470 (format t "~&thread startup sigmask test done~%")
471
472 (sb-debug::enable-debugger)
473 (let* ((main-thread *current-thread*)
474        (interruptor-thread
475         (make-thread (lambda ()
476                        (sleep 2)
477                        (interrupt-thread main-thread #'break)
478                        (sleep 2)
479                        (interrupt-thread main-thread #'continue)))))
480   (with-session-lock (*session*)
481     (sleep 3))
482   (loop while (thread-alive-p interruptor-thread)))
483
484 (format t "~&session lock test done~%")
485
486 (loop repeat 20 do
487       (wait-for-threads
488        (loop for i below 100 collect
489              (sb-thread:make-thread (lambda ())))))
490
491 (format t "~&creation test done~%")
492
493 ;; interrupt handlers are per-thread with pthreads, make sure the
494 ;; handler installed in one thread is global
495 (sb-thread:make-thread
496  (lambda ()
497    (sb-ext:run-program "sleep" '("1") :search t :wait nil)))
498
499 ;;;; Binding stack safety
500
501 (defparameter *x* nil)
502 (defparameter *n-gcs-requested* 0)
503 (defparameter *n-gcs-done* 0)
504
505 (let ((counter 0))
506   (defun make-something-big ()
507     (let ((x (make-string 32000)))
508       (incf counter)
509       (let ((counter counter))
510         (sb-ext:finalize x (lambda () (format t " ~S" counter)
511                                    (force-output)))))))
512
513 (defmacro wait-for-gc ()
514   `(progn
515      (incf *n-gcs-requested*)
516      (loop while (< *n-gcs-done* *n-gcs-requested*))))
517
518 (defun send-gc ()
519   (loop until (< *n-gcs-done* *n-gcs-requested*))
520   (format t "G")
521   (force-output)
522   (sb-ext:gc)
523   (incf *n-gcs-done*))
524
525 (defun exercise-binding ()
526   (loop
527    (let ((*x* (make-something-big)))
528      (let ((*x* 42))
529        ;; at this point the binding stack looks like this:
530        ;; NO-TLS-VALUE-MARKER, *x*, SOMETHING, *x*
531        t))
532    (wait-for-gc)
533    ;; sig_stop_for_gc_handler binds FREE_INTERRUPT_CONTEXT_INDEX. By
534    ;; now SOMETHING is gc'ed and the binding stack looks like this: 0,
535    ;; 0, SOMETHING, 0 (because the symbol slots are zeroed on
536    ;; unbinding but values are not).
537    (let ((*x* nil))
538      ;; bump bsp as if a BIND had just started
539      (incf sb-vm::*binding-stack-pointer* 2)
540      (wait-for-gc)
541      (decf sb-vm::*binding-stack-pointer* 2))))
542
543 (with-test (:name (:binding-stack-gc-safety))
544   (let (threads)
545     (unwind-protect
546          (progn
547            (push (sb-thread:make-thread #'exercise-binding) threads)
548            (push (sb-thread:make-thread (lambda ()
549                                           (loop
550                                            (sleep 0.1)
551                                            (send-gc))))
552                  threads)
553            (sleep 4))
554       (mapc #'sb-thread:terminate-thread threads))))
555
556 (format t "~&binding test done~%")
557
558 ;; Try to corrupt the NEXT-VECTOR. Operations on a hash table with a
559 ;; cyclic NEXT-VECTOR can loop endlessly in a WITHOUT-GCING form
560 ;; causing the next gc hang SBCL.
561 (with-test (:name (:hash-table-thread-safety))
562   (let* ((hash (make-hash-table))
563          (threads (list (sb-thread:make-thread
564                          (lambda ()
565                            (loop
566                             ;;(princ "1") (force-output)
567                             (setf (gethash (random 100) hash) 'h))))
568                         (sb-thread:make-thread
569                          (lambda ()
570                            (loop
571                             ;;(princ "2") (force-output)
572                             (remhash (random 100) hash))))
573                         (sb-thread:make-thread
574                          (lambda ()
575                            (loop
576                             (sleep (random 1.0))
577                             (sb-ext:gc :full t)))))))
578     (unwind-protect
579          (sleep 5)
580       (mapc #'sb-thread:terminate-thread threads))))
581
582 (format t "~&hash table test done~%")
583 #|  ;; a cll post from eric marsden
584 | (defun crash ()
585 |   (setq *debugger-hook*
586 |         (lambda (condition old-debugger-hook)
587 |           (debug:backtrace 10)
588 |           (unix:unix-exit 2)))
589 |   #+live-dangerously
590 |   (mp::start-sigalrm-yield)
591 |   (flet ((roomy () (loop (with-output-to-string (*standard-output*) (room)))))
592 |     (mp:make-process #'roomy)
593 |     (mp:make-process #'roomy)))
594 |#
595
596 (with-test (:name (:condition-variable :notify-multiple))
597   (flet ((tester (notify-fun)
598            (let ((queue (make-waitqueue :name "queue"))
599                  (lock (make-mutex :name "lock"))
600                  (data nil))
601              (labels ((test (x)
602                         (loop
603                            (with-mutex (lock)
604                              (format t "condition-wait ~a~%" x)
605                              (force-output)
606                              (condition-wait queue lock)
607                              (format t "woke up ~a~%" x)
608                              (force-output)
609                              (push x data)))))
610                (let ((threads (loop for x from 1 to 10
611                                     collect
612                                     (let ((x x))
613                                       (sb-thread:make-thread (lambda ()
614                                                                (test x)))))))
615                  (sleep 5)
616                  (with-mutex (lock)
617                    (funcall notify-fun queue))
618                  (sleep 5)
619                  (mapcar #'terminate-thread threads)
620                  ;; Check that all threads woke up at least once
621                  (assert (= (length (remove-duplicates data)) 10)))))))
622     (tester (lambda (queue)
623               (format t "~&(condition-notify queue 10)~%")
624               (force-output)
625               (condition-notify queue 10)))
626     (tester (lambda (queue)
627               (format t "~&(condition-broadcast queue)~%")
628               (force-output)
629               (condition-broadcast queue)))))
630
631 (format t "waitqueue wakeup tests done~%")
632
633 (with-test (:name (:mutex :finalization))
634   (let ((a nil))
635     (dotimes (i 500000)
636       (setf a (make-mutex)))))
637
638 (format t "mutex finalization test done~%")
639
640 ;;; Check that INFO is thread-safe, at least when we're just doing reads.
641
642 (let* ((symbols (loop repeat 10000 collect (gensym)))
643        (functions (loop for (symbol . rest) on symbols
644                         for next = (car rest)
645                         for fun = (let ((next next))
646                                     (lambda (n)
647                                       (if next
648                                           (funcall next (1- n))
649                                           n)))
650                         do (setf (symbol-function symbol) fun)
651                         collect fun)))
652   (defun infodb-test ()
653     (funcall (car functions) 9999)))
654
655 (with-test (:name (:infodb :read))
656   (let* ((ok t)
657          (threads (loop for i from 0 to 10
658                         collect (sb-thread:make-thread
659                                  (lambda ()
660                                    (dotimes (j 100)
661                                      (write-char #\-)
662                                      (finish-output)
663                                      (let ((n (infodb-test)))
664                                        (unless (zerop n)
665                                          (setf ok nil)
666                                          (format t "N != 0 (~A)~%" n)
667                                          (sb-ext:quit)))))))))
668     (wait-for-threads threads)
669     (assert ok)))
670
671 (format t "infodb test done~%")
672
673 (with-test (:name (:backtrace))
674   ;; Printing backtraces from several threads at once used to hang the
675   ;; whole SBCL process (discovered by accident due to a timer.impure
676   ;; test misbehaving). The cause was that packages weren't even
677   ;; thread-safe for only doing FIND-SYMBOL, and while printing
678   ;; backtraces a loot of symbol lookups need to be done due to
679   ;; *PRINT-ESCAPE*.
680   (let* ((threads (loop repeat 10
681                         collect (sb-thread:make-thread
682                                  (lambda ()
683                                    (dotimes (i 1000)
684                                      (with-output-to-string (*debug-io*)
685                                        (sb-debug::backtrace 10))))))))
686     (wait-for-threads threads)))
687
688 (format t "backtrace test done~%")
689
690 (format t "~&starting gc deadlock test: WARNING: THIS TEST WILL HANG ON FAILURE!~%")
691
692 (with-test (:name (:gc-deadlock))
693   ;; Prior to 0.9.16.46 thread exit potentially deadlocked the
694   ;; GC due to *all-threads-lock* and session lock. On earlier
695   ;; versions and at least on one specific box this test is good enough
696   ;; to catch that typically well before the 1500th iteration.
697   (loop
698      with i = 0
699      with n = 3000
700      while (< i n)
701      do
702        (incf i)
703        (when (zerop (mod i 100))
704          (write-char #\.)
705          (force-output))
706        (handler-case
707            (if (oddp i)
708                (sb-thread:make-thread
709                 (lambda ()
710                   (sleep (random 0.001)))
711                 :name (list :sleep i))
712                (sb-thread:make-thread
713                 (lambda ()
714                   ;; KLUDGE: what we are doing here is explicit,
715                   ;; but the same can happen because of a regular
716                   ;; MAKE-THREAD or LIST-ALL-THREADS, and various
717                   ;; session functions.
718                   (sb-thread:with-mutex (sb-thread::*all-threads-lock*)
719                     (sb-thread::with-session-lock (sb-thread::*session*)
720                       (sb-ext:gc))))
721                 :name (list :gc i)))
722          (error (e)
723            (format t "~%error creating thread ~D: ~A -- backing off for retry~%" i e)
724            (sleep 0.1)
725            (incf i)))))
726
727 (format t "~&gc deadlock test done~%")
728 \f
729 (let ((count (make-array 8 :initial-element 0)))
730   (defun closure-one ()
731     (declare (optimize safety))
732     (values (incf (aref count 0)) (incf (aref count 1))
733             (incf (aref count 2)) (incf (aref count 3))
734             (incf (aref count 4)) (incf (aref count 5))
735             (incf (aref count 6)) (incf (aref count 7))))
736   (defun no-optimizing-away-closure-one ()
737     (setf count (make-array 8 :initial-element 0))))
738
739 (defstruct box
740   (count 0))
741
742 (let ((one (make-box))
743       (two (make-box))
744       (three (make-box)))
745   (defun closure-two ()
746     (declare (optimize safety))
747     (values (incf (box-count one)) (incf (box-count two)) (incf (box-count three))))
748   (defun no-optimizing-away-closure-two ()
749     (setf one (make-box)
750           two (make-box)
751           three (make-box))))
752
753 (with-test (:name (:funcallable-instances))
754   ;; the funcallable-instance implementation used not to be threadsafe
755   ;; against setting the funcallable-instance function to a closure
756   ;; (because the code and lexenv were set separately).
757   (let ((fun (sb-kernel:%make-funcallable-instance 0))
758         (condition nil))
759     (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
760     (flet ((changer ()
761              (loop (setf (sb-kernel:funcallable-instance-fun fun) #'closure-one)
762                    (setf (sb-kernel:funcallable-instance-fun fun) #'closure-two)))
763            (test ()
764              (handler-case (loop (funcall fun))
765                (serious-condition (c) (setf condition c)))))
766       (let ((changer (make-thread #'changer))
767             (test (make-thread #'test)))
768         (handler-case
769             (progn
770               ;; The two closures above are fairly carefully crafted
771               ;; so that if given the wrong lexenv they will tend to
772               ;; do some serious damage, but it is of course difficult
773               ;; to predict where the various bits and pieces will be
774               ;; allocated.  Five seconds failed fairly reliably on
775               ;; both my x86 and x86-64 systems.  -- CSR, 2006-09-27.
776               (sb-ext:with-timeout 5
777                 (wait-for-threads (list test)))
778               (error "~@<test thread got condition:~2I~_~A~@:>" condition))
779           (sb-ext:timeout ()
780             (terminate-thread changer)
781             (terminate-thread test)
782             (wait-for-threads (list changer test))))))))
783
784 (format t "~&funcallable-instance test done~%")
785
786 (defun random-type (n)
787   `(integer ,(random n) ,(+ n (random n))))
788
789 (defun subtypep-hash-cache-test ()
790   (dotimes (i 10000)
791     (let ((type1 (random-type 500))
792           (type2 (random-type 500)))
793       (let ((a (subtypep type1 type2)))
794         (dotimes (i 100)
795           (assert (eq (subtypep type1 type2) a))))))
796   (format t "ok~%")
797   (force-output))
798
799 (with-test (:name '(:hash-cache :subtypep))
800   (dotimes (i 10)
801     (sb-thread:make-thread #'subtypep-hash-cache-test)))
802
803 (format t "hash-cache tests done~%")