3

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?

Jazzwave06
  • 1,883
  • 1
  • 11
  • 19
  • Yes, but add an `if (isDisposed == true)` above that and it may turn out that you're asking the wrong question. **Edit** Since you've written that you *only use atomic operations on them*, I presume you're using some kind of a synchronization (`Interlocked`? Although then you're not using a `bool` variable). – vgru Jul 30 '14 at 13:44
  • Yeah of course, because then you're trying to do a read, then a write. This is clearly not atomic. No I'm not. Those flags I'm talking about always are false at initialization. Then some method sets the flag to true, and no other method will ever set it back to false. Operations on them are either a read (A check, if isDisposed then throw) or a write (set it to true). – Jazzwave06 Jul 30 '14 at 13:46
  • Please check http://stackoverflow.com/questions/4269498/volatile-and-thread-memorybarrier-in-c-sharp – TomTom Jul 30 '14 at 13:54

1 Answers1

2

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

illegal-immigrant
  • 8,089
  • 9
  • 51
  • 84