When the field Declaration contains the volatile modifier, the field introduced by this declaration is a loss-prone field.
Because of the optimization technology (IT will reschedule the execution order of commands ),ProgramIn the running environment, if synchronization (such as provided by the lock statement) is not used, access to non-Easy fields may lead to unexpected and unpredictable results. These optimizations can be executed by compilers, runtime systems, or hardware. However, for easy-to-lose fields, the re-sorting during optimization must follow the following rules:
Read an easy-to-lose field is called easy-to-read. The easy-to-lose read feature has the "get Semantics". That is to say, according to the instruction sequence, all references to memory after the easy-to-lose read must be placed behind it during execution.
Writing an easy-to-lose field is called easy-to-write. The easy-to-lose write feature has the release semantics. That is to say, according to the instruction sequence, all references to memory before the easy-to-lose write must be placed at the top of the memory during execution.
These restrictions ensure that all threads observe the easy-to-lose writes executed by any other thread (in the originally scheduled order ). An implementation that complies with this specification is not required: The execution sequence of easy to write data is the same for all the threads being executed. The type of the easy-to-lose field must be one of the following:
Reference type.
Type: byte, sbyte, short, ushort, Int, uint, Char, float, or bool.
The enumeration base type is byte, sbyte, short, ushort, Int, or uint.
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 );
Return;
}
}
}
}
Generate the following output:
Result = 143.
In this example, the method main starts a new thread and the thread runs the thread2 method. This method stores a value in a non-Easy loss field called result, and then stores true in the easy loss field finished. The main thread waits for the finished field to be set to true and then reads the result field. Since finished has been declared as volatile, the value read by the main thread from the field result must be 143. If the finished field is not declared as volatile, the write sequence of finished and result may change. In this way, when the main thread reads the result field, it may not have been assigned a value (so it is the initial value 0 ). Declaring finished as a volatile field can prevent such inconsistency.
More technologies are availableHere