Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c# - Why are immutable objects thread-safe?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What makes an object not thread safe? An object is not thread safe if the value/state of that object can change while a thread is reading it. This generally happens if a second thread changes this object's value while the first thread is reading it.

An immutable object, by definition, cannot change value/state. Since every time you read an immutable object it has the same value/state, you can have any number of threads read that object with no concerns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...