public static int Add(ref int location1,int value)
I was trying to use the Interlocked.Add(ref int location1,int value) method to add to a number in an atomic manner in multi-threading scenario. But I got a question to myself: why does the method return the location1 value again? Instead we could directly use the variable which is passed as "ref".
Some pseudo code below:
int a = 6;
int b = 7;
// some thing else
Interlocked.Add(ref a, b);
// Use the variable 'a' here.
The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads, or when two threads are executing concurrently on separate processors.
Interlock. Exchange returns the original value while performing an atomic operation. The whole point is to provide a locking mechanism. So it is actually two operations: read original value and set new value. Those two together are not atomic.
The Interlocked class provides a number of static methods that perform atomic operations. These can generally be regarded as thread-safe.
Because the variable ref a
could change "again" before Interlocked
returns (or even after it returns and before you use a
). The function instead returns the value it calculated.
Example:
int a = 5;
// on thread 1
int b = Interlocked.Add(ref a, 5); // b = 10
// on thread 2, at the same time
int c = Interlocked.Add(ref a, 5); // c = 15
// on thread 1
Thread.Sleep(1000); // so we are "sure" thread 2 executed
Thread.MemoryBarrier(); // just to be sure we are really reading a
bool x1 = (b == 10); // true
bool x2 = (a == 15); // true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With