通常状况下,只要涉及到多线程编程,程序的复杂性就会显著上升,性能显著降低,BUG出现的几率大大提高。程序员
多线程编程本意是将一段程序并行运行,提高数据处理能力,可是因为大部分状况下都涉及到共有资源的竞争,因此修改资源编程
对象时必须加锁处理。可是锁的实现有不少种方法,下面就来一块儿了解一下在C#语言中几种锁的实现与其性能表现。c#
一、临界区,经过对多线程的串行化来访问公共资源或一段代码,速度快,适合控制数据访问。安全
1 private static object obj = new object(); 2 private static int lockInt; 3 private static void LockIntAdd() 4 { 5 for (var i = 0; i < runTimes; i++) 6 { 7 lock (obj) 8 { 9 lockInt++; 10 } 11 } 12 }
你没看错,c#中的lock语法就是临界区(Monitor)的一个语法糖,这大概是90%以上的.net程序员首先想到的锁,不过大部分人都只是知道多线程
有这么个语法,不知道实际上是以临界区的方式处理资源竞争。ide
二、互斥量,为协调共同对一个共享资源的单独访问而设计的。oop
c#中有一个Mutex类,就在System.Threading命名空间下,Mutex其实就是互斥量,互斥量不仅仅能处理多线程之间的资源竞争,还能处理性能
进程之间的资源竞争,功能是比较强大的,可是开销也很大,性能比较低。测试
1 private static Mutex mutex = new Mutex(); 2 private static int mutexInt; 3 private static void MutexIntAdd() 4 { 5 for (var i = 0; i < runTimes; i++) 6 { 7 mutex.WaitOne(); 8 mutexInt++; 9 mutex.ReleaseMutex(); 10 } 11 }
三、信号量,为控制一个具备有限数量用户资源而设计。atom
1 private static Semaphore sema = new Semaphore(1, 1); 2 private static int semaphoreInt; 3 private static void SemaphoreIntAdd() 4 { 5 for (var i = 0; i < runTimes; i++) 6 { 7 sema.WaitOne(); 8 semaphoreInt++; 9 sema.Release(); 10 } 11 }
四、事 件:用来通知线程有一些事件已发生,从而启动后继任务的开始。
1 public static AutoResetEvent autoResetEvent = new AutoResetEvent(true); 2 private static int autoResetEventInt; 3 private static void AutoResetEventIntAdd() 4 { 5 for (var i = 0; i < runTimes; i++) 6 { 7 if (autoResetEvent.WaitOne()) 8 { 9 autoResetEventInt++; 10 autoResetEvent.Set(); 11 } 12 } 13 }
五、读写锁,这种锁容许在有其余程序正在写的状况下读取资源,因此若是资源容许脏读,用这个比较合适
1 private static ReaderWriterLockSlim LockSlim = new ReaderWriterLockSlim(); 2 private static int lockSlimInt; 3 private static void LockSlimIntAdd() 4 { 5 for (var i = 0; i < runTimes; i++) 6 { 7 LockSlim.EnterWriteLock(); 8 lockSlimInt++; 9 LockSlim.ExitWriteLock(); 10 } 11 }
六、原子锁,经过原子操做Interlocked.CompareExchange实现“无锁”竞争
1 private static int isLock; 2 private static int ceInt; 3 private static void CEIntAdd() 4 { 5 //long tmp = 0; 6 for (var i = 0; i < runTimes; i++) 7 { 8 while (Interlocked.CompareExchange(ref isLock, 1, 0) == 1) { Thread.Sleep(1); } 9 10 ceInt++; 11 Interlocked.Exchange(ref isLock, 0); 12 } 13 }
七、原子性操做,这是一种特例,野外原子性操做自己天生线程安全,因此无需加锁
1 private static int atomicInt; 2 private static void AtomicIntAdd() 3 { 4 for (var i = 0; i < runTimes; i++) 5 { 6 Interlocked.Increment(ref atomicInt); 7 } 8 }
八、不加锁,若是不加锁,那多线程下运行结果确定是错的,这里贴上来比较一下性能
1 private static int noLockInt; 2 private static void NoLockIntAdd() 3 { 4 for (var i = 0; i < runTimes; i++) 5 { 6 noLockInt++; 7 } 8 }
一、测试代码,执行1000,10000,100000,1000000次
1 private static void Run() 2 { 3 var stopwatch = new Stopwatch(); 4 var taskList = new Task[loopTimes]; 5 6 // 多线程 7 Console.WriteLine(); 8 Console.WriteLine($" 线程数:{loopTimes}"); 9 Console.WriteLine($" 执行次数:{runTimes}"); 10 Console.WriteLine($" 校验值应等于:{runTimes * loopTimes}"); 11 12 // AtomicIntAdd 13 stopwatch.Restart(); 14 for (var i = 0; i < loopTimes; i++) 15 { 16 taskList[i] = Task.Factory.StartNew(() => { AtomicIntAdd(); }); 17 } 18 Task.WaitAll(taskList); 19 Console.WriteLine($"{GetFormat("AtomicIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{atomicInt}"); 20 21 // CEIntAdd 22 taskList = new Task[loopTimes]; 23 stopwatch.Restart(); 24 25 for (var i = 0; i < loopTimes; i++) 26 { 27 taskList[i] = Task.Factory.StartNew(() => { CEIntAdd(); }); 28 } 29 Task.WaitAll(taskList); 30 Console.WriteLine($"{GetFormat("CEIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{ceInt}"); 31 32 // LockIntAdd 33 taskList = new Task[loopTimes]; 34 stopwatch.Restart(); 35 36 for (var i = 0; i < loopTimes; i++) 37 { 38 taskList[i] = Task.Factory.StartNew(() => { LockIntAdd(); }); 39 } 40 Task.WaitAll(taskList); 41 Console.WriteLine($"{GetFormat("LockIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{lockInt}"); 42 43 // MutexIntAdd 44 taskList = new Task[loopTimes]; 45 stopwatch.Restart(); 46 47 for (var i = 0; i < loopTimes; i++) 48 { 49 taskList[i] = Task.Factory.StartNew(() => { MutexIntAdd(); }); 50 } 51 Task.WaitAll(taskList); 52 Console.WriteLine($"{GetFormat("MutexIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{mutexInt}"); 53 54 // LockSlimIntAdd 55 taskList = new Task[loopTimes]; 56 stopwatch.Restart(); 57 58 for (var i = 0; i < loopTimes; i++) 59 { 60 taskList[i] = Task.Factory.StartNew(() => { LockSlimIntAdd(); }); 61 } 62 Task.WaitAll(taskList); 63 Console.WriteLine($"{GetFormat("LockSlimIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{lockSlimInt}"); 64 65 // SemaphoreIntAdd 66 taskList = new Task[loopTimes]; 67 stopwatch.Restart(); 68 69 for (var i = 0; i < loopTimes; i++) 70 { 71 taskList[i] = Task.Factory.StartNew(() => { SemaphoreIntAdd(); }); 72 } 73 Task.WaitAll(taskList); 74 Console.WriteLine($"{GetFormat("SemaphoreIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{semaphoreInt}"); 75 76 77 // AutoResetEventIntAdd 78 taskList = new Task[loopTimes]; 79 stopwatch.Restart(); 80 81 for (var i = 0; i < loopTimes; i++) 82 { 83 taskList[i] = Task.Factory.StartNew(() => { AutoResetEventIntAdd(); }); 84 } 85 Task.WaitAll(taskList); 86 Console.WriteLine($"{GetFormat("AutoResetEventIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{autoResetEventInt}"); 87 88 // NoLockIntAdd 89 taskList = new Task[loopTimes]; 90 stopwatch.Restart(); 91 92 for (var i = 0; i < loopTimes; i++) 93 { 94 taskList[i] = Task.Factory.StartNew(() => { NoLockIntAdd(); }); 95 } 96 Task.WaitAll(taskList); 97 Console.WriteLine($"{GetFormat("NoLockIntAdd")}, 总耗时:{stopwatch.ElapsedMilliseconds}毫秒, 校验值:{noLockInt}"); 98 Console.WriteLine(); 99 }
二、线程:10
三、线程:50
1)在各类测试中,不加锁确定是最快的,因此尽可能避免资源竞争致使加锁运行
2)在多线程中Interlocked.CompareExchange始终表现出优越的性能,排在第二位
3)第三位lock,临界区也表现出很好的性能,因此在别人说lock性能低的时候请反驳他
4)第四位是原子性变量(Atomic)操做,不过目前只支持变量的自增自减,适用性不强
5)第五位读写锁(ReaderWriterLockSlim)表现也还能够,而且支持无所读,实用性仍是比较好的
6)剩下的信号量、事件、互斥量,这三种性能最差,固然他们有各自的适用范围,只是在处理资源竞争这方面表现很差
over,就这样吧,睡觉。。。