Interlocked.Increment ?

  • Thread starter Thread starter George Ter-Saakov
  • Start date Start date
G

George Ter-Saakov

What is the purpose of having Interlocked.Increment if it does not work with
variable declared as volatile.

Here is my problem,
Interlocked.Increment increments the variable in thread safe manner.
But at the same time if i want to use variable that could be changed in
another thread i must use volatile (to prevent optimization).

But then i can not use Interlocked.Increment.
So i do not see any benefits of having Interlocked.Increment because i can
not think of any use of it.


Thanks.
George.
 
Hi George,

InterLocked .Increment is not targeted to be used with volatile modifier. I
think if you are using InterLocked class, you don't need to use volatile.
The volatile modifier is usually used for a field that is accessed by
multiple threads without using the lock statement to serialize access.

According to C# Language Specification (10.4.3 Volatile fields), for
non-volatile fields, optimization techniques that reorder instructions can
lead to unexpected and unpredictable results in multi-threaded programs
that access fields without synchronization such as that provided by the
lock-statement. To avoid this problem, we can use volatile modifier to
guarantee safe access to the field.

You can use InterLocked class to serialize access to the field to make it
thread safe.

Regards,

Felix Wu
=============
This posting is provided "AS IS" with no warranties, and confers no rights.


--------------------
 
My understanding is that volatile word needs to be specified so compiler
will know not to optimize access to it.

Basically following code

i = 6;
k = i*8;
will give a result 48 even if i was changed in another thread.
Because compiler will figure out that i is not changed and it can safely
assign k a 48 in runtime.

volatile i = 6;
k = i*8;
Will not be optimized since compiler will know that i could have been
changed.

And in my opinion the variable used in Interlocked.Increment must be
declared as volatile since it's definitely will be changed in different
threads.



George.
 
Hi George,

You are right. We use volatile modifier to tell the optimizer that the
variable should not be moved to a register rather it should be accessed
from memory all the time.This can avoid reading a cached value. In your
case, you can use Interlock.* methods
(Increment/Decrement/Exchange/CompareExchange) to read and write the
variable instead of using volatiles. If I remember correctly, access with
Interlocked.* method is natively volatile.

Regards,

Felix Wu
=============
This posting is provided "AS IS" with no warranties, and confers no rights.


--------------------
From: "George Ter-Saakov" <[email protected]>
References: <[email protected]>
 
Back
Top