vote buttons
12-Dec-2014 04:22 UTC
Super Human

1 Answers

vote buttons

Interlocked class provides a set of static functions which allow a few simple operations to be performed thread safe. Apart from convenience, these functions are much faster than having a lock around an equivalent statement (explained below). First, following is a list of Interlocked functions with explanation in comments.

long counter = 0;
//Increment counter by 1
Interlocked.Increment (ref counter);                              
//Decrement counter by 1
Interlocked.Decrement (ref counter);                              
//Add 10 to counter
Interlocked.Add (ref counter, 10);                                 
//Set counter = 100 and return the original value of counter before it was changed.
//This usually does not require a lock but consider a scenario where
//counter is a 64 bit value and code running on a 32 bit machine.
//In such a scenario the assignment happens in 2 steps for each 32 bit part
//and hence the assignment is not atomic.
var oldCounterValue = Interlocked.Exchange (ref counter, 100);

// Read a 64-bit value atomically into another variable (val)
var val = Interlocked.Read(ref counter);               
// Set counter = 999 if counter == 1000
Interlocked.CompareExchange(ref counter, 999, 1000);  

As I mentioned these statements are faster in most cases and especially on modern CPUs, as these functions execute in a lock free manner or as a single instruction wherever possible, thus avoiding the need for a lock (they do use memory barriers though, to avoid reordering issues etc.) For example CompareExchange function uses the cpu instruction CMPXCHG which allows Comparison and Exchange of values in a single instruction which cannot be pre-empted.

12-Dec-2014 04:23 UTC
Super Human