When should the volatile keyword be used in C#?

前端 未结 10 850
盖世英雄少女心
盖世英雄少女心 2020-11-22 12:04

Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn\'t? In which cases will it save me the use of locking?

相关标签:
10条回答
  • 2020-11-22 12:41

    multiple threads can access a variable. The latest update will be on the variable

    0 讨论(0)
  • 2020-11-22 12:44

    So to sum up all this, the correct answer to the question is: If your code is running in the 2.0 runtime or later, the volatile keyword is almost never needed and does more harm than good if used unnecessarily. I.E. Don't ever use it. BUT in earlier versions of the runtime, it IS needed for proper double check locking on static fields. Specifically static fields whose class has static class initialization code.

    0 讨论(0)
  • 2020-11-22 12:46

    I don't think there's a better person to answer this than Eric Lippert (emphasis in the original):

    In C#, "volatile" means not only "make sure that the compiler and the jitter do not perform any code reordering or register caching optimizations on this variable". It also means "tell the processors to do whatever it is they need to do to ensure that I am reading the latest value, even if that means halting other processors and making them synchronize main memory with their caches".

    Actually, that last bit is a lie. The true semantics of volatile reads and writes are considerably more complex than I've outlined here; in fact they do not actually guarantee that every processor stops what it is doing and updates caches to/from main memory. Rather, they provide weaker guarantees about how memory accesses before and after reads and writes may be observed to be ordered with respect to each other. Certain operations such as creating a new thread, entering a lock, or using one of the Interlocked family of methods introduce stronger guarantees about observation of ordering. If you want more details, read sections 3.10 and 10.5.3 of the C# 4.0 specification.

    Frankly, I discourage you from ever making a volatile field. Volatile fields are a sign that you are doing something downright crazy: you're attempting to read and write the same value on two different threads without putting a lock in place. Locks guarantee that memory read or modified inside the lock is observed to be consistent, locks guarantee that only one thread accesses a given chunk of memory at a time, and so on. The number of situations in which a lock is too slow is very small, and the probability that you are going to get the code wrong because you don't understand the exact memory model is very large. I don't attempt to write any low-lock code except for the most trivial usages of Interlocked operations. I leave the usage of "volatile" to real experts.

    For further reading see:

    • Understand the Impact of Low-Lock Techniques in Multithreaded Apps
    • Sayonara volatile
    0 讨论(0)
  • 2020-11-22 12:47

    If you are using .NET 1.1, the volatile keyword is needed when doing double checked locking. Why? Because prior to .NET 2.0, the following scenario could cause a second thread to access an non-null, yet not fully constructed object:

    1. Thread 1 asks if a variable is null. //if(this.foo == null)
    2. Thread 1 determines the variable is null, so enters a lock. //lock(this.bar)
    3. Thread 1 asks AGAIN if the variable is null. //if(this.foo == null)
    4. Thread 1 still determines the variable is null, so it calls a constructor and assigns the value to the variable. //this.foo = new Foo();

    Prior to .NET 2.0, this.foo could be assigned the new instance of Foo, before the constructor was finished running. In this case, a second thread could come in (during thread 1's call to Foo's constructor) and experience the following:

    1. Thread 2 asks if variable is null. //if(this.foo == null)
    2. Thread 2 determines the variable is NOT null, so tries to use it. //this.foo.MakeFoo()

    Prior to .NET 2.0, you could declare this.foo as being volatile to get around this problem. Since .NET 2.0, you no longer need to use the volatile keyword to accomplish double checked locking.

    Wikipedia actually has a good article on Double Checked Locking, and briefly touches on this topic: http://en.wikipedia.org/wiki/Double-checked_locking

    0 讨论(0)
提交回复
热议问题