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