[tests] Don't starve the main thread by doing GCs
[mono.git] / mono / tests / thread-suspend-selfsuspended.cs
1
2 using System;
3 using System.Threading;
4
5 class Driver
6 {
7         public static void Main ()
8         {
9                 bool finished = false;
10                 int can_gc = 0;
11
12                 Thread t1 = Thread.CurrentThread;
13
14                 Thread t2 = new Thread (() => {
15                         while (!finished) {
16                                 int local_can_gc = can_gc;
17                                 if (local_can_gc > 0 && Interlocked.CompareExchange (ref can_gc, local_can_gc - 1, local_can_gc) == local_can_gc)
18                                         GC.Collect ();
19
20                                 try {
21                                         t1.Resume ();
22                                 } catch (ThreadStateException) {
23                                 }
24
25                                 Thread.Yield ();
26                         }
27                 });
28
29                 t2.Start ();
30
31                 Thread.Sleep (10);
32
33                 for (int i = 0; i < 50 * 40 * 5; ++i) {
34                         Interlocked.Increment (ref can_gc);
35                         Thread.CurrentThread.Suspend ();
36                         if ((i + 1) % (50) == 0)
37                                 Console.Write (".");
38                         if ((i + 1) % (50 * 40) == 0)
39                                 Console.WriteLine ();
40                 }
41
42                 finished = true;
43
44                 t2.Join ();
45         }
46 }