The Interlocked Class


One other class that is related to synchronization is Interlocked. This class offers an alternative to the other synchronization features when all you need to do is change the value of a shared variable. The methods provided by Interlocked guarantee that their operations are performed as a single, uninterruptible operation. Thus, no other synchronization is needed. Interlocked provides static methods that add two integers, increment an integer, decrement an integer, compare and set an object, exchange objects, and obtain a 64-bit value. All of these operations take place without interruption.

The following program demonstrates two Interlocked methods: Increment( ) and Decrement( ). Here are the forms of these methods that will be used:

 public static int Increment(ref int v) public static int Decrement(ref int v)

Here, v is the value to be incremented or decremented.

 // Use Interlocked operations. using System; using System.Threading; // A shared resource. class SharedRes {   public static int count = 0; } // This thread increments SharedRes.count. class IncThread {   public Thread thrd;   public IncThread(string name) {     thrd = new Thread(this.run);     thrd.Name = name;     thrd.Start();   }   // Entry point of thread.   void run() {     for(int i=0; i<5; i++) {       Interlocked.Increment(ref SharedRes.count);       Console.WriteLine(thrd.Name + " count is " + SharedRes.count);     }   } } // This thread decrements SharedRes.count. class DecThread {   public Thread thrd;   public DecThread(string name) {     thrd = new Thread(this.run);     thrd.Name = name;     thrd.Start();   }   // Entry point of thread.   void run() {     for(int i=0; i<5; i++) {       Interlocked.Decrement(ref SharedRes.count);       Console.WriteLine(thrd.Name + " count is " + SharedRes.count);     }   } } class InterlockedDemo {   public static void Main() {     // Construct two threads.     IncThread mt1 = new IncThread("Increment Thread");     DecThread mt2 = new DecThread("Decrement Thread");     mt1.thrd.Join();     mt2.thrd.Join();   } }




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net