According to MSDN:
The volatile keyword indicates that a field might be modified by
multiple threads that are executing at the same time. Fields that are
declared volatile are not subject to compiler optimizations that
assume access by a single thread. This ensures that the most
up-to-date value is present in the field at all times.
Please notice the last sentence:
This ensures that the most up-to-date value is present in the field at all times.
However, there's a problem with this keyword.
I've read that it can change order of instructions:
First instruction Second instruction Can they be swapped?
Read Read No
Read Write No
Write Write No
Write Read Yes! <----
This means John sets a value to a volatile field, and later Paul wants to read the field,
Paul is getting the old value!
What is going here ? Isn't that it's main job ?
I know there are other solutions, but my question is about the volatile keyword.
Should I (as a programmer) need to prevent using this keyword - because of such weird behavior ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…