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