Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 642
kolosy Avatar asked Jun 16 '09 16:06

kolosy


People also ask

Is volatile expensive?

Generally speaking, on most modern processors a volatile load is comparable to a normal load. A volatile store is about 1/3 the time of a montior-enter/monitor-exit. This is seen on systems that are cache coherent. To answer the OP's question, volatile writes are expensive while the reads usually are not.

What is the use of volatile keyword?

The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.

What is the use of volatile keyword in Java with example?

For Java, “volatile” tells the compiler that the value of a variable must never be cached as its value may change outside of the scope of the program itself.

What is the use of volatile keyword in C#?

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. The compiler, the runtime system, and even hardware may rearrange reads and writes to memory locations for performance reasons.


1 Answers

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.

like image 106
Skurmedel Avatar answered Oct 24 '22 12:10

Skurmedel