Quantcast
Channel: Volatile vs. Interlocked vs. lock - Stack Overflow
Viewing all articles
Browse latest Browse all 11

Answer by V. S. for Volatile vs. Interlocked vs. lock

$
0
0

I would like to add to mentioned in the other answers the difference between volatile, Interlocked, and lock:

The volatile keyword can be applied to fields of these types:

  • Reference types.
  • Pointer types (in an unsafe context). Note that although the pointer itself can be volatile, the object that it points to cannot. In otherwords, you cannot declare a "pointer" to be "volatile".
  • Simple types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
  • An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.
  • Generic type parameters known to be reference types.
  • IntPtr and UIntPtr.

Other types, including double and long, cannot be marked "volatile"because reads and writes to fields of those types cannot be guaranteedto be atomic. To protect multi-threaded access to those types offields, use the Interlocked class members or protect access using thelock statement.


Viewing all articles
Browse latest Browse all 11

Trending Articles