前面几篇咱们介绍了线程同步的临界区、互斥量、事件、信号量四种方式。 .NET中线程同步的方式多的让人看了眼花缭乱,究竟该怎么去理解呢?其实,咱们抛开.NET环境看线程同步,无非是执行两种操做:一是互斥/加锁,目的是保证临界区代码操做的“原子性”;另外一种是信号灯操做,目的是保证多个线程按照必定顺序执行,如生产者线程要先于消费者线程执行。.NET中线程同步的类无非是对这两种方式的封装,目的归根结底均可以归结为实现互斥/加锁或者是信号灯这两种方式,只是它们的适用场合有所不一样。下面咱们下来总结一下以前几种同步方式的区别,而后再讲一下原子操做Interlockedspa
1、几种同步方法的区别操作系统
lock和Monitor是.NET用一个特殊结构实现的,Monitor对象是彻底托管的、彻底可移植的,而且在操做系统资源要求方面可能更为有效,同步速度较快,但不能跨进程同步。lock(Monitor.Enter和Monitor.Exit方法的封装),主要做用是锁定临界区,使临界区代码只能被得到锁的线程执行。Monitor.Wait和Monitor.Pulse用于线程同步,相似信号操做,我的感受使用比较复杂,容易形成死锁。线程
互斥体Mutex和事件对象EventWaitHandler属于内核对象,利用内核对象进行线程同步,线程必需要在用户模式和内核模式间切换,因此通常效率很低,但利用互斥对象和事件对象这样的内核对象,能够在多个进程中的各个线程间进行同步。code
互斥体Mutex相似于一个接力棒,拿到接力棒的线程才能够开始跑,固然接力棒一次只属于一个线程(Thread Affinity),若是这个线程不释放接力棒(Mutex.ReleaseMutex),那么没办法,其余全部须要接力棒运行的线程都知道能等着看热闹。对象
EventWaitHandle 类容许线程经过发信号互相通讯。一般,一个或多个线程在 EventWaitHandle 上阻止,直到一个未阻止的线程调用 Set 方法,以释放一个或多个被阻止的线程。blog
2、原子操做Interlocked进程
Interlocked提供不少方法执行原子操做,下边将详细介绍事件
一、Increment自增效果 资源
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InterLocked { class Program { static void Main(string[] args) { for (int i = 0; i < 20; i++) { Thread t = new Thread(Run); t.Start(); } Console.Read(); } static int count = 0; static Mutex mutex = new Mutex(); static void Run() { mutex.WaitOne(); Thread.Sleep(100); Console.WriteLine("当前数字:{0}", Interlocked.Increment(ref count)); mutex.ReleaseMutex(); } } }
二、Decrement自减操做rem
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InterLocked { class Program { static void Main(string[] args) { for (int i = 0; i < 20; i++) { Thread t = new Thread(Run); t.Start(); } Console.Read(); } static int count = 20; static Mutex mutex = new Mutex(); static void Run() { mutex.WaitOne(); Thread.Sleep(100); Console.WriteLine("当前数字:{0}", Interlocked.Decrement(ref count)); mutex.ReleaseMutex(); } } }
三、Add加法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InterLocked { class Program { static void Main(string[] args) { int i = 10; Interlocked.Add(ref i, 20); Console.WriteLine(i); //i=30 Console.ReadKey(); } } }
四、Exchange 赋值操做
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace InterLocked { class Program { static void Main(string[] args) { int i = 10; Interlocked.Exchange(ref i, 30); Console.WriteLine(i); //i=30 Console.ReadKey(); } } }
InterLocked类还有不少方法,这里就不一一介绍了。。。。。。。。。。。。。。