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