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