前面几篇我们介绍了线程同步的临界区、互斥量、事件、信号量四种方式。 .NET中线程同步的方式多的让人看了眼花缭乱,究竟该怎么去理解呢?其实,我们抛开.NET环境看线程同步,无非是执行两种操作:一是互斥/加锁,目的是保证临界区代码操作的“原子性”;另一种是信号灯操作,目的是保证多个线程按照一定顺序执行,如生产者线程要先于消费者线程执行。.NET中线程同步的类无非是对这两种方式的封装,目的归根结底都可以归结为实现互斥/加锁或者是信号灯这两种方式,只是它们的适用场合有所不同。下面我们下来总结一下之前几种同步方式的区别,然后再讲一下原子操作Interlocked
一、几种同步方法的区别
lock和Monitor是.NET用一个特殊结构实现的,Monitor对象是完全托管的、完全可移植的,并且在操作系统资源要求方面可能更为有效,同步速度较快,但不能跨进程同步。lock(Monitor.Enter和Monitor.Exit方法的封装),主要作用是锁定临界区,使临界区代码只能被获得锁的线程执行。Monitor.Wait和Monitor.Pulse用于线程同步,类似信号操作,个人感觉使用比较复杂,容易造成死锁。
互斥体Mutex和事件对象EventWaitHandler属于内核对象,利用内核对象进行线程同步,线程必须要在用户模式和内核模式间切换,所以一般效率很低,但利用互斥对象和事件对象这样的内核对象,可以在多个进程中的各个线程间进行同步。
互斥体Mutex类似于一个接力棒,拿到接力棒的线程才可以开始跑,当然接力棒一次只属于一个线程(Thread Affinity),如果这个线程不释放接力棒(Mutex.ReleaseMutex),那么没办法,其他所有需要接力棒运行的线程都知道能等着看热闹。
EventWaitHandle 类允许线程通过发信号互相通信。通常,一个或多个线程在 EventWaitHandle 上阻止,直到一个未阻止的线程调用 Set 方法,以释放一个或多个被阻止的线程。
二、原子操作Interlocked
Interlocked提供很多方法执行原子操作,下边将详细介绍
1、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(); } } }
2、Decrement自减操作
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(); } } }
3、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(); } } }
4、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类还有很多方法,这里就不一一介绍了。。。。。。。。。。。。。。