Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Interlocked.Add() method have to return a value?

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.
like image 580
Ranganatha Avatar asked Mar 04 '15 09:03

Ranganatha


People also ask

When should you use the interlocked class?

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.

What is interlocked exchange?

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.

Is interlocked exchange thread safe?

The Interlocked class provides a number of static methods that perform atomic operations. These can generally be regarded as thread-safe.


1 Answers

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
like image 169
xanatos Avatar answered Sep 22 '22 17:09

xanatos