<p>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?</p>

[{'answer_id': 72328, 'author': 'Joseph Daigle', 'author_id': 507, 'author_profile': 'https://Stackoverflow.com/users/507', 'pm_score': 4, 'selected': False, 'text': '<p>The CLR likes to optimize instructions, so when you access a field in code it might not always access the current value of the field (it might be from the stack, etc). Marking a field as <code>volatile</code> ensures that the current value of the field is accessed by the instruction. This is useful when the value can be modified (in a non-locking scenario) by a concurrent thread in your program or some other code running in the operating system.</p>\n\n<p>You obviously lose some optimization, but it does keep the code more simple.</p>\n'}, {'answer_id': 72368, 'author': 'Dr. Bob', 'author_id': 12182, 'author_profile': 'https://Stackoverflow.com/users/12182', 'pm_score': 5, 'selected': False, 'text': '<p>From <a href="http://msdn.microsoft.com/en-us/library/x13ttww7(VS.71).aspx" rel="noreferrer">MSDN</a>:\nThe volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.</p>\n'}, {'answer_id': 72453, 'author': 'Benoit', 'author_id': 10703, 'author_profile': 'https://Stackoverflow.com/users/10703', 'pm_score': 5, 'selected': False, 'text': '<p>Sometimes, the compiler will optimize a field and use a register to store it. If thread 1 does a write to the field and another thread accesses it, since the update was stored in a register (and not memory), the 2nd thread would get stale data.</p>\n\n<p>You can think of the volatile keyword as saying to the compiler "I want you to store this value in memory". This guarantees that the 2nd thread retrieves the latest value.</p>\n'}, {'answer_id': 73076, 'author': 'Skizz', 'author_id': 1898, 'author_profile': 'https://Stackoverflow.com/users/1898', 'pm_score': 6, 'selected': False, 'text': "<p>If you want to get slightly more technical about what the volatile keyword does, consider the following program (I'm using DevStudio 2005):</p>\n\n<pre><code>#include &lt;iostream&gt;\nvoid main()\n{\n  int j = 0;\n  for (int i = 0 ; i &lt; 100 ; ++i)\n  {\n    j += i;\n  }\n  for (volatile int i = 0 ; i &lt; 100 ; ++i)\n  {\n    j += i;\n  }\n  std::cout &lt;&lt; j;\n}\n</code></pre>\n\n<p>Using the standard optimised (release) compiler settings, the compiler creates the following assembler (IA32):</p>\n\n<pre><code>void main()\n{\n00401000  push        ecx  \n  int j = 0;\n00401001  xor         ecx,ecx \n  for (int i = 0 ; i &lt; 100 ; ++i)\n00401003  xor         eax,eax \n00401005  mov         edx,1 \n0040100A  lea         ebx,[ebx] \n  {\n    j += i;\n00401010  add         ecx,eax \n00401012  add         eax,edx \n00401014  cmp         eax,64h \n00401017  jl          main+10h (401010h) \n  }\n  for (volatile int i = 0 ; i &lt; 100 ; ++i)\n00401019  mov         dword ptr [esp],0 \n00401020  mov         eax,dword ptr [esp] \n00401023  cmp         eax,64h \n00401026  jge         main+3Eh (40103Eh) \n00401028  jmp         main+30h (401030h) \n0040102A  lea         ebx,[ebx] \n  {\n    j += i;\n00401030  add         ecx,dword ptr [esp] \n00401033  add         dword ptr [esp],edx \n00401036  mov         eax,dword ptr [esp] \n00401039  cmp         eax,64h \n0040103C  jl          main+30h (401030h) \n  }\n  std::cout &lt;&lt; j;\n0040103E  push        ecx  \n0040103F  mov         ecx,dword ptr [__imp_std::cout (40203Ch)] \n00401045  call        dword ptr [__imp_std::basic_ostream&lt;char,std::char_traits&lt;char&gt; &gt;::operator&lt;&lt; (402038h)] \n}\n0040104B  xor         eax,eax \n0040104D  pop         ecx  \n0040104E  ret              \n</code></pre>\n\n<p>Looking at the output, the compiler has decided to use the ecx register to store the value of the j variable. For the non-volatile loop (the first) the compiler has assigned i to the eax register. Fairly straightforward. There are a couple of interesting bits though - the lea ebx,[ebx] instruction is effectively a multibyte nop instruction so that the loop jumps to a 16 byte aligned memory address. The other is the use of edx to increment the loop counter instead of using an inc eax instruction. The add reg,reg instruction has lower latency on a few IA32 cores compared to the inc reg instruction, but never has higher latency. </p>\n\n<p>Now for the loop with the volatile loop counter. The counter is stored at [esp] and the volatile keyword tells the compiler the value should always be read from/written to memory and never assigned to a register. The compiler even goes so far as to not do a load/increment/store as three distinct steps (load eax, inc eax, save eax) when updating the counter value, instead the memory is directly modified in a single instruction (an add mem,reg). The way the code has been created ensures the value of the loop counter is always up-to-date within the context of a single CPU core. No operation on the data can result in corruption or data loss (hence not using the load/inc/store since the value can change during the inc thus being lost on the store). Since interrupts can only be serviced once the current instruction has completed, the data can never be corrupted, even with unaligned memory.</p>\n\n<p>Once you introduce a second CPU to the system, the volatile keyword won't guard against the data being updated by another CPU at the same time. In the above example, you would need the data to be unaligned to get a potential corruption. The volatile keyword won't prevent potential corruption if the data cannot be handled atomically, for example, if the loop counter was of type long long (64 bits) then it would require two 32 bit operations to update the value, in the middle of which an interrupt can occur and change the data.</p>\n\n<p>So, the volatile keyword is only good for aligned data which is less than or equal to the size of the native registers such that operations are always atomic.</p>\n\n<p>The volatile keyword was conceived to be used with IO operations where the IO would be constantly changing but had a constant address, such as a memory mapped UART device, and the compiler shouldn't keep reusing the first value read from the address.</p>\n\n<p>If you're handling large data or have multiple CPUs then you'll need a higher level (OS) locking system to handle the data access properly.</p>\n"}, {'answer_id': 17530556, 'author': 'Ohad Schneider', 'author_id': 67824, 'author_profile': 'https://Stackoverflow.com/users/67824', 'pm_score': 9, 'selected': True, 'text': '<p>I don\'t think there\'s a better person to answer this than <a href="https://ericlippert.com/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/" rel="noreferrer">Eric Lippert</a> (emphasis in the original): </p>\n\n<blockquote>\n  <p>In C#, "volatile" means not only "make sure that the compiler and the\n  jitter do not perform any code reordering or register caching\n  optimizations on this variable". It also means "tell the processors to\n  do whatever it is they need to do to ensure that I am reading the\n  latest value, even if that means halting other processors and making\n  them synchronize main memory with their caches".</p>\n  \n  <p>Actually, that last bit is a lie. The true semantics of volatile reads\n  and writes are considerably more complex than I\'ve outlined here; in\n  fact <strong>they do not actually guarantee that every processor stops what it\n  is doing</strong> and updates caches to/from main memory. Rather, <strong>they provide\n  weaker guarantees about how memory accesses before and after reads and\n  writes may be observed to be ordered with respect to each other</strong>.\n  Certain operations such as creating a new thread, entering a lock, or\n  using one of the Interlocked family of methods introduce stronger\n  guarantees about observation of ordering. If you want more details,\n  read sections 3.10 and 10.5.3 of the C# 4.0 specification.</p>\n  \n  <p>Frankly, <strong>I discourage you from ever making a volatile field</strong>. Volatile\n  fields are a sign that you are doing something downright crazy: you\'re\n  attempting to read and write the same value on two different threads\n  without putting a lock in place. Locks guarantee that memory read or\n  modified inside the lock is observed to be consistent, locks guarantee\n  that only one thread accesses a given chunk of memory at a time, and so\n  on. The number of situations in which a lock is too slow is very\n  small, and the probability that you are going to get the code wrong\n  because you don\'t understand the exact memory model is very large. I\n  don\'t attempt to write any low-lock code except for the most trivial\n  usages of Interlocked operations. I leave the usage of "volatile" to\n  real experts.</p>\n</blockquote>\n\n<p>For further reading see:</p>\n\n<ul>\n<li><a href="https://learn.microsoft.com/archive/msdn-magazine/2005/october/understanding-low-lock-techniques-in-multithreaded-apps" rel="noreferrer">Understand the Impact of Low-Lock Techniques in Multithreaded Apps</a></li>\n<li><a href="http://joeduffyblog.com/2010/12/04/sayonara-volatile/" rel="noreferrer">Sayonara volatile</a></li>\n</ul>\n'}, {'answer_id': 19765698, 'author': 'user2943601', 'author_id': 2943601, 'author_profile': 'https://Stackoverflow.com/users/2943601', 'pm_score': -1, 'selected': False, 'text': '<p>multiple threads can access a variable.\nThe latest update will be on the variable</p>\n'}, {'answer_id': 22079568, 'author': 'AndrewTek', 'author_id': 2970689, 'author_profile': 'https://Stackoverflow.com/users/2970689', 'pm_score': 6, 'selected': False, 'text': '<p>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:</p>\n\n<ol>\n<li>Thread 1 asks if a variable is null.\n//if(this.foo == null)</li>\n<li>Thread 1 determines the variable is null, so enters a lock.\n//lock(this.bar)</li>\n<li>Thread 1 asks AGAIN if the variable is null.\n//if(this.foo == null)</li>\n<li>Thread 1 still determines the variable is null, so it calls a constructor and assigns the value to the variable.\n//this.foo = new Foo();</li>\n</ol>\n\n<p>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:</p>\n\n<ol>\n<li>Thread 2 asks if variable is null. \n//if(this.foo == null)</li>\n<li>Thread 2 determines the variable is NOT null, so tries to use it.\n//this.foo.MakeFoo()</li>\n</ol>\n\n<p>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.</p>\n\n<p>Wikipedia actually has a good article on Double Checked Locking, and briefly touches on this topic:\n<a href="http://en.wikipedia.org/wiki/Double-checked_locking" rel="noreferrer">http://en.wikipedia.org/wiki/Double-checked_locking</a></p>\n'}, {'answer_id': 35274777, 'author': 'Aliaksei Maniuk', 'author_id': 1370029, 'author_profile': 'https://Stackoverflow.com/users/1370029', 'pm_score': 1, 'selected': False, 'text': '<p>The compiler sometimes changes the order of statements in code to optimize it. Normally this is not a problem in single-threaded environment, but it might be an issue in multi-threaded environment. See following example: \n</p>\n\n<pre><code> private static int _flag = 0;\n private static int _value = 0;\n\n var t1 = Task.Run(() =&gt;\n {\n     _value = 10; /* compiler could switch these lines */\n     _flag = 5;\n });\n\n var t2 = Task.Run(() =&gt;\n {\n     if (_flag == 5)\n     {\n         Console.WriteLine("Value: {0}", _value);\n     }\n });\n</code></pre>\n\n<p>If you run t1 and t2, you would expect no output or "Value: 10" as the result. It could be that the compiler switches line inside t1 function. If t2 then executes, it could be that _flag has value of 5, but _value has 0. So expected logic could be broken. </p>\n\n<p>To fix this you can use <strong>volatile</strong> keyword that you can apply to the field. This statement disables the compiler optimizations so you can force the correct order in you code.</p>\n\n<pre><code>private static volatile int _flag = 0;\n</code></pre>\n\n<p>You should use <strong>volatile</strong> only if you really need it, because it disables certain compiler optimizations, it will hurt performance. It\'s also not supported by all .NET languages (Visual Basic doesn\'t support it), so it hinders language interoperability.</p>\n'}, {'answer_id': 53779862, 'author': 'Paul Easter', 'author_id': 3583929, 'author_profile': 'https://Stackoverflow.com/users/3583929', 'pm_score': 1, 'selected': False, 'text': "<p>So to sum up all this, the correct answer to the question is:\nIf 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.</p>\n"}, {'answer_id': 58905467, 'author': 'Christina Katsakoula', 'author_id': 12388334, 'author_profile': 'https://Stackoverflow.com/users/12388334', 'pm_score': 3, 'selected': False, 'text': '<p>I found this article by <a href="https://www.infoworld.com/article/3229360/how-to-use-the-volatile-keyword-in-c.html" rel="noreferrer">Joydip Kanjilal</a> very helpful!</p>\n\n<p><code>When you mark an object or a variable as volatile, it becomes a candidate for volatile reads and writes. It should be noted that in C# all memory writes are volatile irrespective of whether you are writing data to a volatile or a non-volatile object. However, the ambiguity happens when you are reading data. When you are reading data that is non-volatile, the executing thread may or may not always get the latest value. If the object is volatile, the thread always gets the most up-to-date value</code></p>\n\n<p>I\'ll just leave it here for reference</p>\n'}, {'answer_id': 65144763, 'author': 'Yarl', 'author_id': 5987619, 'author_profile': 'https://Stackoverflow.com/users/5987619', 'pm_score': 3, 'selected': False, 'text': '<p>Simply looking into the official page for <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile" rel="noreferrer">volatile keyword</a> you can see an example of typical usage.</p>\n<pre><code>public class Worker\n{\n    public void DoWork()\n    {\n        bool work = false;\n        while (!_shouldStop)\n        {\n            work = !work; // simulate some work\n        }\n        Console.WriteLine(&quot;Worker thread: terminating gracefully.&quot;);\n    }\n    public void RequestStop()\n    {\n        _shouldStop = true;\n    }\n    \n    private volatile bool _shouldStop;\n}\n</code></pre>\n<blockquote>\n<p>With the volatile modifier added to the declaration of _shouldStop in place, you\'ll always get the same results. However, without that modifier on the _shouldStop member, the behavior is unpredictable.</p>\n</blockquote>\n<p>So this is definitely not something <em>downright crazy</em>.</p>\n<p>There exists <a href="https://en.wikipedia.org/wiki/Cache_coherence" rel="noreferrer">Cache coherence</a> that is responsible for CPU caches consistency.</p>\n<p>Also if CPU employs <a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/january/csharp-the-csharp-memory-model-in-theory-and-practice-part-2" rel="noreferrer">strong memory model</a> (as x86)</p>\n<blockquote>\n<p>As a result, reads and writes of volatile fields require no special instructions on the x86: Ordinary reads and writes (for example, using the MOV instruction) are sufficient.</p>\n</blockquote>\n<p>Example from C# 5.0 specification (chapter 10.5.3)</p>\n<pre><code>using System;\nusing System.Threading;\nclass Test\n{\n    public static int result;   \n    public static volatile bool finished;\n    static void Thread2() {\n        result = 143;    \n        finished = true; \n    }\n    static void Main() {\n\n        finished = false;\n        new Thread(new ThreadStart(Thread2)).Start();\n\n        for (;;) {\n            if (finished) {\n                Console.WriteLine(&quot;result = {0}&quot;, result);\n                return;\n            }\n        }\n    }\n}\n</code></pre>\n<p><strong>produces the output: result = 143</strong></p>\n<blockquote>\n<p>If the field finished had not been declared volatile, then it would be permissible for the store to result to be visible to the main thread after the store to finished, and hence for the main thread to read the value 0 from the field result.</p>\n</blockquote>\n<p>Volatile behavior is platform dependent so you should always consider using <code>volatile</code> when needed by case to be sure it satisfies your needs.</p>\n<p>Even <code>volatile</code> could not prevent (all kind of) reordering (<a href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/january/csharp-the-csharp-memory-model-in-theory-and-practice-part-2" rel="noreferrer">C# - The C# Memory Model in Theory and Practice, Part 2</a>)</p>\n<blockquote>\n<p>Even though the write to A is volatile and the read from A_Won is also volatile, the fences are both one-directional, and in fact allow this reordering.</p>\n</blockquote>\n<p>So I believe if you want to know when to use <code>volatile</code> (vs <code>lock</code> vs <code>Interlocked</code>) you should get familiar with memory fences (full, half) and needs of a synchronization. Then you get your precious answer yourself for your good.</p>\n'}]
['https://Stackoverflow.com/questions/72275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3389/']