class Unit {
private readonly string name;
private readonly double scale;
public Unit(string name, double scale) {
this.name = name;
this.scale = scale,
}
public string Name { get { return name; } }
public string Scale { get { return scale; } }
private static Unit gram = new Unit("Gram", 1.0);
public Unit Gram { get { return gram; } }
}
Multiple threads have access to Unit.Gram. Why is it ok for multiple threads simultaneously read Unit.Gram.Title?
My concern is that they are referring to the same memory location. One thread starts reading that memory, so isn’t it “locked out” then? Does the .NET handle synchronization for this critical section underneath? Or am I wrong in thinking that simultaneous reading needs synchronization?
I think your question turns out not to be about thread-safety or immutablity but about the (very) low level details of memory access.
And that is a hefty subject but the short answer is: Yes, two threads (and more important, 2+ CPU’s) can read (and/or write) the same piece of memory simultaneously.
And as long as the content of that memory area is immutable, all problems are solved. When it can change, there is a whole range of issues, the
volatilekeyword and theInterlockedclass are some of the tools we use to solve those.