Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use System.Threading.Interlocked.Decrement instead of minus?

I converted some c# code to vb.net and the converter.telerik.com turned this:

i--;

into this:

System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1)

Whats up with all the fancy-ness?

like image 589
swolff1978 Avatar asked Dec 01 '09 20:12

swolff1978


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.

What is interlocked increment?

Increments a specified variable and stores the result, as an atomic operation.

What are Interlocked functions?

The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. They also perform operations on variables in an atomic manner. The threads of different processes can use these functions if the variable is in shared memory.


2 Answers

Michał Piaskowski's comment triggered the following explanation:

The semantics of i-- in C# are to return the current value of i (i.e., the value before the decrement occurs) and then decrement i by one.

So, we need to convert that to VB. We can not use i -= 1 because this does not return the current value of i before the decrement. So, we need an operation that will decrement i but return the value of i before the decrement, something like:

Function DoPostDecrement(ByRef i As Integer) As Integer
    i -= 1
    Return i + 1
End Function

But this suggests using the following to avoid having to write a method to perform the above:

System.Math.Max(
    someValueThatIsEqualToiMinusOne,
    someValueThatIsEqualtoiBeforeTheDecrement
)

But VB.NET won't let you use i -= 1 or i = i - 1 in place of someValueThatIsEqualToiMinusOne. However, System.Threading.Interlocked.Decrement(i) is legit and equal to the value of i - 1. Once you do that, because parameters are evaluated left to right, someValueThatIsEqualtoiBeforeTheDecrement should be i + 1 (at that point the decrement has been performed to i + 1 is the pre-decrement value.

Note that the above method DoPostDecrement and the System.Math.Max, System.Threading.Interlocked.Decrement construct could have different semantics in a multithreaded context.

like image 104
jason Avatar answered Nov 04 '22 02:11

jason


The Interlocked operation is atomic; in multithreaded contexts you can safely use it without holding a lock, if you're careful.

like image 31
Skirwan Avatar answered Nov 04 '22 00:11

Skirwan