c5d5e4aa26adab5eb928aa7a58f1bdfb5a015c89
[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 DateTime targetTime;
9         static bool finished() {
10                 DateTime now = DateTime.UtcNow;
11                 return now > targetTime;
12         }
13
14         public static void Main ()
15         {
16                 int gcCount = 0;
17                 int joinCount = 0;
18                 targetTime = DateTime.UtcNow.AddSeconds(30);
19
20                 Thread gcThread = new Thread (() => {
21                         while (!finished()) {
22                                 GC.Collect ();
23                                 gcCount++;
24                                 Thread.Sleep (1);
25                         }
26                 });
27
28                 gcThread.Start ();
29
30                 // Create threads then join them for 30 seconds nonstop while GCs occur once per ms
31                 while (!finished()) {
32                         BlockingCollection<Thread> threads = new BlockingCollection<Thread> (new ConcurrentQueue<Thread> (), 128);
33
34                         Thread joinThread = new Thread (() => {
35                                 for (int i = 0; ; ++i) {
36                                         Thread t = threads.Take ();
37                                         if (t == null)
38                                                 break;
39                                         t.Join ();
40
41                                         // Uncomment this and run with MONO_LOG_LEVEL=info MONO_LOG_MASK=gc
42                                         // to see GC/join balance in real time
43                                         //Console.Write ("*");
44                                 }
45                         });
46                         joinThread.Start ();
47                         
48                         const int makeThreads = 10*1000;
49                         for (int i = 0; i < makeThreads; ++i) {
50                                 Thread t = new Thread (() => { Thread.Yield (); });
51                                 t.Start ();
52
53                                 threads.Add (t);
54                         }
55
56                         threads.Add (null);
57                         joinThread.Join ();
58
59                         joinCount += makeThreads;
60                         Console.WriteLine("Performed {0} GCs, created {1} threads. Finished? {2}", gcCount, joinCount, finished());
61                 }
62                 gcThread.Join ();
63         }
64 }