ms link:The hyperlink login is visible.
The volatile keyword indicates that a field can be modified by multiple threads executing at the same time. Fields declared as volatile are not restricted by compiler optimization (assuming they are accessed by a single thread). This ensures that the field is rendered with the most recent value at all times.
The volatile modifier is typically used for fields that are accessed by multiple threads but do not serialize the access using a lock statement.
Volatile keywords can be applied to the following types of fields:
- Citation type.
- Pointer type (in an unsafe context). Note that while the pointer itself can be mutable, the object it points to cannot be mutable. In other words, "pointer to a mutable object" cannot be declared.
- types such as sbyte, byte, short, ushort, int, uint, char, float, and bool.
- An enum type with one of the following base types: byte, sbyte, short, ushort, int, or uint.
- Generic type parameters that are known to be reference types.
- IntPtr and UIntPtr.
Variable keywords can only be applied to fields of a class or structure.Local variables cannot be declared as volatile。
No more nonsense, write a loop to test it:
Let's test it 10,000 times in a loop,found that the output of a values is correct, but,It doesn't explainvolatile is thread safeBecause, if you test it many times, you will find that there will be calculation errors! Because there is a chance of a correct result and a chance of a wrong result
Code:
Let's test 100,000 loops again, and we can find that the value of a is incorrect, because the smaller the number of loops, the smaller the chance of error, and the error is not so obvious, just like there was no error after 10,000 loops just now.
At this time, we add a lock to test, and it can be seen that the value of a is calculated correctly as we expected.
Code:
Summary: volatile does not guarantee thread safety, as you can see in the example above.
|