June 14, 2011

Volatile

Volatile on Msdn
Keep forgetting to use this. The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread. Volatile means that read/write operations will always target the main memory not a cached copy, it does not imply access to a variable is made thread safe through its usage.
Good explanantion of volatile/non-volatile reads and writes
Understand the Impact of Low-Lock Techniques in Multithreaded Apps

Watch out for warnings when using a volatile variable in an Interlocked operation. Use #pragma to remove it:
#pragma warning disable 420  // Volatile passed as reference to the interlocked API
  System.Threading.Interlocked.Exchange<SomeType>(ref this.somObject, newSomeObject);
#pragma warning restore 420

No comments: