[tests] Add stress testing and reduce sgen normal testing time (#4653)
[mono.git] / mono / tests / sgen-new-threads-collect.cs
1
2 using System;
3 using System.Collections.Concurrent;
4 using System.Threading;
5
6 class Driver
7 {
8         static TestTimeout timeout;
9
10         public static void Main ()
11         {
12                 int gcCount = 0;
13                 int joinCount = 0;
14                 TestTimeout timeout = TestTimeout.Start(TimeSpan.FromSeconds(TestTimeout.IsStressTest ? 60 : 1));
15
16                 Thread gcThread = new Thread (() => {
17                         while (timeout.HaveTimeLeft) {
18                                 GC.Collect ();
19                                 gcCount++;
20                                 Thread.Sleep (1);
21                         }
22                 });
23
24                 gcThread.Start ();
25
26                 // Create threads then join them for 1 seconds (120 for stress tests) nonstop while GCs occur once per ms
27                 while (timeout.HaveTimeLeft) {
28                         BlockingCollection<Thread> threads = new BlockingCollection<Thread> (new ConcurrentQueue<Thread> (), 128);
29
30                         Thread joinThread = new Thread (() => {
31                                 for (int i = 0; ; ++i) {
32                                         Thread t = threads.Take ();
33                                         if (t == null)
34                                                 break;
35                                         t.Join ();
36
37                                         // Uncomment this and run with MONO_LOG_LEVEL=info MONO_LOG_MASK=gc
38                                         // to see GC/join balance in real time
39                                         //Console.Write ("*");
40                                 }
41                         });
42                         joinThread.Start ();
43                         
44                         const int makeThreads = 10*1000;
45                         for (int i = 0; i < makeThreads; ++i) {
46                                 Thread t = new Thread (() => { Thread.Yield (); });
47                                 t.Start ();
48
49                                 threads.Add (t);
50                         }
51
52                         threads.Add (null);
53                         joinThread.Join ();
54
55                         joinCount += makeThreads;
56                         Console.WriteLine("Performed {0} GCs, created {1} threads. Finished? {2}", gcCount, joinCount, !timeout.HaveTimeLeft);
57                 }
58                 gcThread.Join ();
59         }
60 }