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