Multi-threaded programming Learning Series --- Interlocked class

Look at the piece of code

class Program
{
    static void Main(string[] args)
    {
        var counter = new Counter();
        var t1 = new Thread(() => TestCount(counter));
        var t2 = new Thread(() => TestCount(counter));
        var t3 = new Thread(() => TestCount(counter));
        t1.Start();
        t2.Start();
        t3.Start();
        t1.Join();
        t2.Join();
        t3.Join();
        Console.WriteLine($"totalCount is {counter.Count}");

        var counterNoLock = new CounterNoLock();
        var t4 = new Thread(() => TestCount(counterNoLock));
        var t5 = new Thread(() => TestCount(counterNoLock));
        var t6 = new Thread(() => TestCount(counterNoLock));
        t4.Start();
        t5.Start();
        t6.Start();
        t4.Join();
        t5.Join();
        t6.Join();

        Console.WriteLine($"Interlocked totalCount is {counterNoLock.Count}");

        Console.ReadKey();
    }

    static void TestCount(CounterBase model)
    {
        for (int i = 0; i < 10000; i++)
        {
            model.Increment();
            model.Decrement();
        }
    }

}
//计数基类
abstract class CounterBase
{
    public abstract void Increment();
    public abstract void Decrement();
}

//计数类
class Counter : CounterBase
{
    private int _count;
    public int Count
    {
        get
        {
            return _count;
        }
    }

    public override void Increment()
    {
        _count++;
    }
    public override void Decrement()
    {
        _count--;
    }
}
//计数类
class CounterNoLock : CounterBase
{
    private int _count;
    public int Count
    {
        get
        {
            return _count;
        }
    }

    public override void Increment()
    {
        Interlocked.Increment(ref _count);
    }
    public override void Decrement()
    {
        Interlocked.Decrement(ref _count);
    }
}

The results
Here Insert Picture Description
works
runtime code that creates three objects run TestCounter method, the method of execution increment or decrement operation of an object, Counter object is not thread-safe, will encounter race conditions, so the result is the value of the first example uncertain, it may be zero, or it may for others.
We can solve this problem by locking the object, but this will make the other thread is blocked, and by means of Interlocked class, you can get the right result without the need to lock an object, Interlocked provides a method derived from the basic mathematical operations Increment, Decrement, and Add, etc. without using the lock when to help us re-write the Counter class.


Published 37 original articles · won praise 3 · Views 6333

Guess you like

Origin blog.csdn.net/huan13479195089/article/details/88875352