Search code examples
c#multithreadingvolatile

What is the cost of the volatile keyword in a multiprocessor system?


we're running into performance issues, and one potential culprit is a centralized use of a volatile singleton. the specific code is of the form

class foo {
  static volatile instance;
  static object l = new object();

  public static foo Instance {
    if (instance == null)
      lock(l) {
        if (instance == null)
          instance = new foo();
      }

    return foo();
  }
}

this is running on an 8-way box, and we're seeing context switching to the tune of 500,000 per second. typical system resources are fine - 25% cpu util, 25% memory util, low IO, no paging, etc.

does using a volatile field induce a memory barrier or any kind of cpu cache reload? or does it just go after main memory every time, for that field only?


Solution

  • lock does induce a memory barrier, so if you are always accessing instance in a lock you don't need the volatile.

    According to this site:

    The C# volatile keyword implements acquire and release semantics, which implies a read memory barrier on read and a write memory barrier on write.