classProgram
{
StaticvoidMain (string[] args)
{
Console.WriteLine ("Increment Counter");
varc =NewCounter ();
varT1 =NewThread (() = Testcounter (c));
vart2 =NewThread (() = Testcounter (c));
varT3 =NewThread (() = Testcounter (c));
T1. Start ();
T2. Start ();
T3. Start ();
T1. Join ();
T2. Join ();
T3. Join ();
Console.WriteLine ("Total count:{0}", C.count);
Console.WriteLine ("End Increment");
varC1 =NewCounternolock ();
T1 =NewThread (() = Testcounter (c));
t2 =NewThread (() = Testcounter (c));
T3 =NewThread (() = Testcounter (c));
T1. Start ();
T2. Start ();
T3. Start ();
T1. Join ();
T2. Join ();
T3. Join ();
Console.WriteLine ("Total count:{0}", C1. Count);
Console.WriteLine ("End Counternolock");
}
StaticvoidTestcounter (counterbase c)
{
for(inti =0; I <10000; i++)
{
C.increment ();
C.decrement ();
}
}
classCounter:counterbase
{
Privateint_count;
PublicintCount {Get{return_count; } }
PublicOverridevoidIncrement ()
{
_count++;
}
PublicOverridevoidDecrement ()
{
_count--;
}
}
classCounternolock:counterbase
{
Privateint_count;
PublicintCount {Get{return_count; } }
Public OverridevoidIncrement ()
{
Interlocked.Increment (ref_count);
}
PublicOverridevoidDecrement ()
{
Interlocked.decrement (ref_count);
}
}
AbstractclassCounterbase
{
Public AbstractvoidIncrement ();
PublicAbstractvoidDecrement ();
}
}
C # interlock guarantees data consistency