1 using System; 2 using System.Threading; 3 4 public class InterlockTest 5 { 6 public int test; 7 public int add; 8 public int rem; 9 10 static int s_test; 11 Main()12 public static int Main() { 13 int a,b; 14 15 InterlockTest it = new InterlockTest (); 16 17 it.test = 0; 18 int c = Interlocked.Exchange (ref it.test, 1); 19 if (c != 0) 20 return 1; 21 22 if (it.test != 1) 23 return 2; 24 25 it.test = -2; 26 c = Interlocked.CompareExchange (ref it.test, 1, -2); 27 if (c != -2) 28 return 3; 29 30 if (it.test != 1) 31 return 4; 32 33 a = 10; 34 c = Interlocked.Exchange (ref a, 5); 35 if (c != 10) 36 return 5; 37 if (a != 5) 38 return 5; 39 40 a = 1; 41 b = Interlocked.Increment (ref a); 42 if (a != 2) 43 return 5; 44 if (b != 2) 45 return 6; 46 47 a = 2; 48 b = Interlocked.Decrement (ref a); 49 if (b != 1) 50 return 7; 51 if (a != 1) 52 return 8; 53 54 string s = IncTest (); 55 if (s != "A1") 56 return 9; 57 58 s = IncTest (); 59 if (s != "A2") 60 return 10; 61 62 Thread.MemoryBarrier (); 63 64 interlocked_regalloc1 (); 65 66 Console.WriteLine ("done!"); 67 68 return 0; 69 } 70 71 public static object[] buckets; 72 public static object segmentCache; 73 interlocked_regalloc1()74 public static int interlocked_regalloc1 () { 75 int segment = 0; 76 buckets = new object [10]; 77 78 if (buckets[segment] == null) { 79 object newSegment = new Object (); 80 segmentCache = Interlocked.CompareExchange (ref buckets[segment], newSegment, null) == null ? null : newSegment; 81 } 82 return 0; 83 } 84 IncTest()85 public static string IncTest () { 86 return "A" + Interlocked.Increment (ref s_test); 87 } 88 } 89