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