如何线程安全是不可变的对象? [英] How thread safe are immutable objects?

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

问题描述

都说不可变对象是线程安全的,但是这是为什么?

取在多核CPU上运行以下情形:

Take the following scenario running on a multi core CPU:

  • 核心1为内存位置读取一个对象的0x100 并缓存在核心1的L1 / L2高速缓存;
  • 在GC的位置内存收集这些对象,因为它已成为资格和的0x100 可用于新的对象;
  • 在酷睿2的分配(immutable)的对象,它位于地址的0x100 ;
  • 核心1获取一个对这个新对象,并在内存中的位置的0x100 读取它。
  • Core 1 reads an object at memory location 0x100 and it is cached in the L1/L2 cache of Core 1;
  • The GC collects this object at that memory location because it has become eligible and 0x100 becomes available for new objects;
  • Core 2 allocates an (immutable) object which is located at address 0x100;
  • Core 1 gets a reference to this new object and reads it at memory location 0x100.

在这种情况下,当核心1要求在位置值的0x100 是有可能,它从L1 / L2缓存读取过时的数据?我的直觉说,记忆闸门还在这里需要确保核心1读取正确的数据。

In this situation, when Core 1 asks for the value at location 0x100 is it possible that it reads the stale data from its L1/L2 cache? My intuition says that a memory gate is still needed here to ensure that Core 1 reads the correct data.

时的上述分析正确,是需要记忆闸门,还是我失去了一些东西?

Is the above analysis correct and is a memory gate required, or am I missing something?

更新:

我在这里描述的情况是一个更复杂的版本,每次GC做了收集的时间会发生什么。当GC收集,内存重新排序。这意味着它们的物理位置的对象被设在的变化和该L1 / L2必须被无效。大致同样适用于上述示例

The situation I describe here is a more complex version of what happens every time the GC does a collect. When the GC collects, memory is reordered. This means that the physical location the object was located at changes and that L1/L2 must be invalidated. Roughly the same applies to the example above.

既然是合理的期望,.NET确保重新排序内存后,不同的内核看到正确的内​​存状态,上述情况将不会是一个问题了。

Since it is reasonable to expect that .NET ensures that after reordering memory, different cores see the correct memory state, the above situation will not be a problem too.

推荐答案

对象的不变性是不是在你的情况下,真正的问题。相反,您的描述的问题围绕基准,列表或其它系统,其指向的对象旋转。当然这将需要某种技术来确保旧对象不再availble的对可能已试图访问它的线程

The object's immutability isn't the real question in your scenario. Rather, your description's issue revolves around the reference, list, or other system which points to the object. It would of course need some sort of technique to make sure the old object is no longer availble to the thread which may have tried to access it.

真正的指向不可变对象的线程安全是的的不需要写一堆code生产线的安全。相反的框架,操作系统,CPU(和其他任何)做的工作给你。

The real point to immutable object's thread safety is that you don't need to write a bunch of code to produce thread safety. Rather the framework, OS, CPU (and whatever else) do the work for you.

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

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