C#多线程编程(6)--线程安全2 互锁构造Interlocked

在线程安全1中,我介绍了线程同步的意义和一种实现线程同步的方法:volatile。volatile关键字属于原子操作的一种,若对一个关键字使用volatile,很多时候会显得很“浪费”,因为只有在并发访问的情况下才需要“易变”读写,单线程访问时并不需要。在命名空间System.Threading命名空间中提供了InterLock类,该类中提供了一些原子方法。本文来介绍如何使用这些方法。

  互锁

  在抢占式系统中,一个线程在执行到任何阶段都有可能被其他线程“打断”,原子操作能够保证该操作不被其他线程打断,其他线程的“打断”只可能发生在该操作的之前或之后。InterLock类中的方法就是”原子“式的,最常用的方法有:

public static class InterLock{ // return (++location) public static int Increment(ref int location); // return(--location) public static int Decrement(ref int location); // return(location += value) //注意,也可能是负数,从而实现减法运算。 public static int Add(ref int location, int value) // int old = location; location = value; return old; public static int Exchange(ref int location, int value); //old = location1; //if(location1 = comparand) location1 = value; //return old; public static int CompareExchange(ref int location1, int value, int comparand); ... }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpfdsg.html