Jon Jagger
Table of Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Notes DownloadECMA-334 C# Language Specificationpreviousnextprevious at this levelnext at this level 17 Classesprevious at this levelnext at this level 17.4 Fieldsprevious at this levelnext at this level 17.4.3 Volatile fields Paragraph 11 When a field-declaration includes a volatile modifier, the fields introduced by that declaration are volatile fields. 2 For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected and unpredictable results in multi-threaded programs that access fields without synchronization such as that provided by the lock-statement (§15.12). 3 These optimizations can be performed by the compiler, by the runtime system, or by hardware. 4 For volatile fields, such reordering optimizations are restricted: Paragraph 21 These restrictions ensure that all threads will observe volatile writes performed by any other thread in the order in which they were performed. 2 A conforming implementation is not required to provide a single total ordering of volatile writes as seen from all threads of execution. 3 The type of a volatile field must be one of the following: [Example: The example
using System;  
using System.Threading;  
class Test  
   public static int result;  
   public static volatile bool finished;  
   static void Thread2() {  
      result = 143;  
      finished = true;  
   static void Main() {  
      finished = false;  
      // Run Thread2() in a new thread  
      new Thread(new ThreadStart(Thread2)).Start();  
      // Wait for Thread2 to signal that it has a result by setting  
      // finished to true.  
      for (;;) {  
         if (finished) {  
            Console.WriteLine("result = {0}", result);  
produces the output:
result = 143  
In this example, the method Main starts a new thread that runs the method Thread2. This method stores a value into a non-volatile field called result, then stores true in the volatile field finished. The main thread waits for the field finished to be set to true, then reads the field result. Since result has been declared volatile, the main thread must read the value 143 from the field result. 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. Declaring finished as a volatile field prevents any such inconsistency. end example]
{ JSL }
Jagger Software Ltd
Company # 4070126
VAT # 762 5213 42
Valid HTML 4.01Valid CSS