class Program
{
static void Main()
{
Console.WriteLine("Start");
var c = new Counter();
var t1 = new Thread(() => TestCounter(c));
var t2 = new Thread(() => TestCounter(c));
var t3 = new Thread(() => TestCounter(c));
t1.Start();
t2.Start();
t3.Start();
Console.WriteLine("Total:{0}", c.Count);
var d = new CounterWithLock();
var d1 = new Thread(() => TestCounter(d));
var d2 = new Thread(() => TestCounter(d));
var d3 = new Thread(() => TestCounter(d));
d1.Start();
d2.Start();
d3.Start();
Console.WriteLine("Total:{0}", d.Count);
//Console.ReadKey();
}
static void TestCounter(CounterBase c)
{
for (var i = 0; i < 10000000; i++)
{
c.Increment();
c.Decrement();
}
}
class Counter : CounterBase
{
private int _counter;
public int Count { get { return _counter; } }
public override void Increment()
{
_counter++;
}
public override void Decrement()
{
_counter--;
}
}
class CounterWithLock : CounterBase
{
private int _counter;
public int Count { get { return _counter; } }
public readonly object _synvRoot = new object();
public override void Increment()
{
lock (_synvRoot)
{
_counter++;
}
}
public override void Decrement()
{
lock (_synvRoot)
{
_counter--;
}
}
}
abstract class CounterBase
{
public abstract void Increment();
public abstract void Decrement();
}
}
{
static void Main()
{
Console.WriteLine("Start");
var c = new Counter();
var t1 = new Thread(() => TestCounter(c));
var t2 = new Thread(() => TestCounter(c));
var t3 = new Thread(() => TestCounter(c));
t1.Start();
t2.Start();
t3.Start();
Console.WriteLine("Total:{0}", c.Count);
var d = new CounterWithLock();
var d1 = new Thread(() => TestCounter(d));
var d2 = new Thread(() => TestCounter(d));
var d3 = new Thread(() => TestCounter(d));
d1.Start();
d2.Start();
d3.Start();
Console.WriteLine("Total:{0}", d.Count);
//Console.ReadKey();
}
static void TestCounter(CounterBase c)
{
for (var i = 0; i < 10000000; i++)
{
c.Increment();
c.Decrement();
}
}
class Counter : CounterBase
{
private int _counter;
public int Count { get { return _counter; } }
public override void Increment()
{
_counter++;
}
public override void Decrement()
{
_counter--;
}
}
class CounterWithLock : CounterBase
{
private int _counter;
public int Count { get { return _counter; } }
public readonly object _synvRoot = new object();
public override void Increment()
{
lock (_synvRoot)
{
_counter++;
}
}
public override void Decrement()
{
lock (_synvRoot)
{
_counter--;
}
}
}
abstract class CounterBase
{
public abstract void Increment();
public abstract void Decrement();
}
}