От: | mrTwister | ||
Дата: | 09.04.15 08:05 | ||
Оценка: |
class BoxedInt
{
public int Value { get; set; }
}
class LazyInit
{
volatile BoxedInt _box;
public int LazyGet()
{
var b = _box; // Read 1
if (b == null)
{
lock(this)
{
b = new BoxedInt();
b.Value = 42; // Write 1
_box = b; // Write 2
}
}
return b.Value; // Read 2
}
}
In this example, LazyGet is always guaranteed to return “42.” However, if the _box field were not volatile, LazyGet would be allowed to return “0” for two reasons: the reads could get reordered, or the writes could get reordered.