You use volatile
/Thread.MemoryBarrier()
when you want to access a variable across threads without locking.
Variables that are atomic, like an int
for example, are always read and written whole at once. That means that you will never get half of the value before another thread changes it and the other half after it has changed. Because of that you can safely read and write the value in different threads without syncronising.
However, the compiler may optimize away some reads and writes, which you prevent with the volatile
keyword. If you for example have a loop like this:
sum = 0;
foreach (int value in list) {
sum += value;
}
The compiler may actually do the calculations in a processor register and only write the value to the sum
variable after the loop. If you make the sum
variable volatile
, the compiler will generate code that reads and writes the variable for every change, so that it's value is up to date throughout the loop.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…