Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can use this example to demonstrate the different behavior with and without <code>volatile</code>. <strong>This example must be compiled using a Release build and ran outside of the debugger</strong><sup>1</sup>. Experiment by adding and removing the <code>volatile</code> keyword to the <code>stop</code> flag.</p> <p>What happens here is that the read of <code>stop</code> in the <code>while</code> loop is reordered so that it occurs before the loop if <code>volatile</code> is omitted. This prevents the thread from ending even after the main thread set the <code>stop</code> flag to <code>true</code>.</p> <pre><code>class Program { static bool stop = false; public static void Main(string[] args) { var t = new Thread(() =&gt; { Console.WriteLine("thread begin"); bool toggle = false; while (!stop) { toggle = !toggle; } Console.WriteLine("thread end"); }); t.Start(); Thread.Sleep(1000); stop = true; Console.WriteLine("stop = true"); Console.WriteLine("waiting..."); // The Join call should return almost immediately. // With volatile it DOES. // Without volatile it does NOT. t.Join(); } } </code></pre> <p>It should also be noted that subtle changes to this example can reduce its probability of reproducibility. For example, adding <code>Thread.Sleep</code> (perhaps to simulate thread interleaving) will itself introduce a memory barrier and thus the similar semantics of the <code>volatile</code> keyword. I suspect <code>Console.WriteLine</code> introduces implicit memory barriers or otherwise prevents the jitter from using the instruction reordering operation. Just keep that in mind if you start messing with the example too much.</p> <hr> <p><sup>1</sup><em>I believe that framework version prior to 2.0 do not include this reordering optimization. That means you should be able to reproduce this behavior with version 2.0 and higher, but not the earlier versions.</em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload