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