CodePlexProject Hosting for Open Source Software

**Usage**

.Net provides atomic operations for variables that are shared by multiple threads .These operation are exposed by Interlocked class.

Concurrent Extensions Library (CEL) with it's **InterlockedEx** class provides a broader range of atomic operations like multiplying, bitwise AND, OR, XOR and more...

The following example computes a mathematical power in parallel in a thread safe way, by using InterlockedEx class.

class Mul { /// <summary> /// Holds the accumulated multiplied value which can be /// accessed by multiple threads. /// This variable must be accessed in a thread safe way /// </summary> int _total = 0; public Mul(int initial) { _total = initial; } /// <summary> /// Retruns the total value /// </summary> public int Total { get { return _total; } } /// <summary> /// Multiplies the running total with the specified factor, /// in a thread safe way /// </summary> public void MultiplyTotal(int factor) { //This method multiplies _total with factor, //saves the product in _total and returns the product atomically InterlockedEx.Mul(ref _total, factor); } }

class Program { static void Main(string[] args) { //the base int x = 2; //the power int y = 30; //compute the power int res = Power(x, y); Console.WriteLine("{0} raised to the power of {1} = {2}.", x, y, res); Console.ReadLine(); } /// <summary> /// Raises x to the power of y in parallel /// </summary> static int Power(int x,int y) { Mul m = new Mul(x); //x is multiplied y times in a thread safe manner Parallel.For(1, y , (i) => { m.MultiplyTotal(x); }); return m.Total; } }

The program's output is:

2 raised to the power of 30 = 1073741824

**Concept**

InterlockedEx behaves the same as Interlocked class:

- It does not block any thread
- Operations (function calls) are atomic - doing the operation, getting the result and assigning it to the shared variable are atomic.
- The shared variable is manipulated in a thread safe manner
- Method calls are very fast

InterlockedEx contains operations like - bitwise AND, OR, XOR, mathematical minimum, mathematical maximum, integer multiplication.

CEL Future releases will include more atomic operations, and other implementations that enrich the concurrernt APIs which .Net exposes.

**API**

Last edited Nov 28, 2012 at 9:57 AM by brin_zohar, version 30