C# 线程同步计数存在的问题

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace Thread_synchronization_problem
{
    class Program
    {
        static void Main(string[] args)
        {
            int x = 0;
            const int iterationNumber = 5000000;//迭代次数
            Stopwatch sw = Stopwatch.StartNew();//初始化sw
            for (int i = 0; i < iterationNumber; i++)
            {
                x++;
            }
            Console.WriteLine("不使用锁的情况下花费时间:{0}ms",sw.ElapsedMilliseconds);
            sw.Start();//重置时间
            for (int i = 0; i < iterationNumber; i++)
            {
                Interlocked.Increment(ref x);//带锁的递增
            }
            Console.WriteLine("使用锁的情况下花费时间:{0}ms", sw.ElapsedMilliseconds);
            Console.ReadLine();
        }
    }
}

可以看出使用锁的情况花费的时间是不使用锁的几倍;

原文地址:https://www.cnblogs.com/lbonet/p/7306267.html