为什么不可变对象是线程安全的? [英] Why are immutable objects thread-safe?

查看:127
本文介绍了为什么不可变对象是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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; } }
}

多个线程有机会获得 Unit.Gram 。为什么确定为同时读取多个线程 Unit.Gram.Title

Multiple threads have access to Unit.Gram. Why is it ok for multiple threads simultaneously read Unit.Gram.Title?

我担心的是,他们指的是同一个内存位置。一个线程开始读取内存,这样是不是锁定呢?对于是否下这个关键部分的.NET处理同步?还是我错在想,同时读取需要同步?

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.

这是一个沉重的问题,但简单的答案是:是的,两个线程(也是更重要的,2 + CPU的)可以同时读取(和/或写)的同一块内存。

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 volatile keyword and the Interlocked class are some of the tools we use to solve those.

这篇关于为什么不可变对象是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆