Search code examples
c#thread-safetyvolatile

Does volatile keyword ensure thread's cache update?


I'm currently developping an highly concurrent application, and I'm wondering if the volatile keyword can be used to ensure all threads have the latest value. I only use the volatile keyword on boolean, and I only use atomic operations on them. For example:

private volatile bool isDisposed;
public void Dispose() {
   isDisposed = true; // Will all threads see that update?
}

Also, is there a better way to force a cache update on all threads?


Solution

  • Yes, see http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/

    Volatile read: refreshes thread cache before - yes, flushes thread cache after - no

    Volatile write: refreshes thread cache before - no, Flushes thread cache after - yes

    More readings on topic from the same author (highly recommend): The C# Memory Model in Theory and Practice, The C# Memory Model in Theory and Practice 2