I have something like the following in C#:
private double _x;
private bool _xCalculated;
private double GetX() {
if (!_xCalculated) {
_x = ... // some relatively expensive calculation
_xCalculated = true;
}
return _x;
}
My question is, is this thread-safe? As far as I can tell, the worst outcome of this is that two or more threads enter this method at the same time and calculate _x multiple times, but the result is guaranteed to be the same for any instance of this class, so that’s not a particularly huge problem.
Is my understanding of this correct?
A few observations:
While I think the x86 memory ordering guarantees make this safe I’m not entirely sure about that. The memory ordering guarantees of .net have been strengthened recently(I think in .net 4) to match the guarantees of x86.
Memory Model in .net
More on memory ordering
This states that stores are not reordered in .net which I think means that your code is safe. But lockless programming is hard, so I might be overlooking some subtle issues. Perhaps the read in the if clause can cause problems.
I recommend not using this code unless you’re a threading expert and really really need the performance. Else just use something more explicit like locks. Locks are not that expensive if they’re not contended.