初学多线程(一)--保护共享资源

1.共享资源未被保护,被多个线程并行访问,会发生资源分配上的冲突,两种方法保护共享资源
ps:共享资源像静态类中的字段,方法
How to protect shared resources from concurrent access?

1.使用 Interlocked.Increment(字段) 
  //在System.Threading
 class Program
    {
        static int total = 0;
        static void Main(string[] args)
        {
            Stopwatch sp = Stopwatch.StartNew();
            Thread t1 = new Thread(AddToMillion);
            Thread t2 = new Thread(AddToMillion);
            Thread t3 = new Thread(AddToMillion);
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("the total = " + total .ToString ());
            sp.Stop();
            Console.WriteLine("ticks = "+sp.ElapsedTicks);
        }
        static void AddToMillion()
        {
            for (int i = 0; i < 1000000; i++)
            {
                 Interlocked.Increment(total);
            }
        }
    }
   运行结果:the total = 30000
           ticks = 117078
2.使用lock对code session 进行锁定
//使用lock时要创建一个私有的静态object对象
 // private static object obj = new object();
 class Program
    {
        static int total = 0;
        static void Main(string[] args)
        {
            Stopwatch sp = Stopwatch.StartNew();
            Thread t1 = new Thread(AddToMillion);
            Thread t2 = new Thread(AddToMillion);
            Thread t3 = new Thread(AddToMillion);
            t1.Start();
            t2.Start();
            t3.Start();
            t1.Join();
            t2.Join();
            t3.Join();
            Console.WriteLine("the total = " + total .ToString ());
            sp.Stop();
            Console.WriteLine("ticks = "+ sp.ElapsedTicks);
        }
        static object obj = new object();
        static void AddToMillion()
        {
            for (int i = 0; i < 1000000; i++)
            {
                 lock(obj )
                 {
                     total++;
                 }
            }
        }
    }
运行结果:total= 3000000
        ticks = 334236    

2.Interlocked类只能对int/long类型的字段addition/subtraction(increment , decrement ,add etc),这个类包含自增自减的方法,所以Interlocked.Increment(total),中total不用写成total++

你可能感兴趣的:(C#学习)