13.07.2015 Views

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

C# Language Specification - Willy .Net

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 17 Classesusing System;namespace Program1{public class Utils{public static readonly int X = 1;}}namespace Program2{class Test}{}static void Main() {Console.WriteLine(Program1.Utils.X);}The Program1 and Program2 namespaces denote two programs that are compiled separately. BecauseProgram1.Utils.X is declared as a static readonly field, the value output by the Console.WriteLinestatement is not known at compile-time, but rather is obtained at run-time. Thus, if the value of X is changed andProgram1 is recompiled, the Console.WriteLine statement will output the new value even if Program2 isn’trecompiled. However, had X been a constant, the value of X would have been obtained at the time Program2 wascompiled, and would remain unaffected by changes in Program1 until Program2 is recompiled. end example]17.4.3 Volatile fieldsWhen a field-declaration includes a volatile modifier, the fields introduced by that declaration are volatilefields. For non-volatile fields, optimization techniques that reorder instructions can lead to unexpected andunpredictable results in multi-threaded programs that access fields without synchronization such as that providedby the lock-statement (§15.12). These optimizations can be performed by the compiler, by the runtime system, orby hardware. For volatile fields, such reordering optimizations are restricted:• A read of a volatile field is called a volatile read. A volatile read has “acquire semantics”; that is, it isguaranteed to occur prior to any references to memory that occur after it in the instruction sequence.• A write of a volatile field is called a volatile write. A volatile write has “release semantics”; that is, it isguaranteed to happen after any memory references prior to the write instruction in the instruction sequence.These restrictions ensure that all threads will observe volatile writes performed by any other thread in the order inwhich they were performed. A conforming implementation is not required to provide a single total ordering ofvolatile writes as seen from all threads of execution. The type of a volatile field must be one of the following:• A reference-type.• The type byte, sbyte, short, ushort, int, uint, char, float, or bool.• An enum-type having an enum base type of byte, sbyte, short, ushort, int, or uint.[Example: The exampleusing System;using System.Threading;class Test{public static int result;public static volatile bool finished;static void Thread2() {result = 143;finished = true;}223

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!