是整数吗?线程安全?
我知道在 .Net 中所有 32 位类型(例如,int
、bool
等)都是线程安全的。也就是说,不会有部分写入(根据规范)。
但是,这同样适用于int吗?
(可为空的int)?
I know that in .Net all 32-bit types (e.g, int
, bool
, etc) are thread safe. That is, there won't be a partial write (according to the specifications).
But, does the same apply for int?
(nullable int)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个问题的措辞很糟糕,因此到目前为止的答案很混乱。问题应该是“对 int 类型变量的读取和写入是否保证是原子的?”
不,绝对不是。规范在这一点上非常明确:
线程完全有可能从可为 null 类型的共享内存变量中读取部分写入的值。
例如,假设你有一个 int?变量 x 目前的值为 null。因此,它包含一个设置为零的 int 和一个设置为 false 的 bool。现在在另一个线程上将可空 int“5”写入 x。另一个线程从 x 读取不可空 int 0 是完全合法的,因为可以在将 5 设置为 int 之前设置 bool 中的“true”。
The question is poorly worded, and hence the confusion in the answers so far. The question should be "are reads and writes to a variable of type int? guaranteed to be atomic?"
No, absolutely not. The spec is extremely clear on this point:
It is entirely possible for a thread to read a partially written value from a shared-memory variable of nullable type.
For example, suppose you have an int? variable x which at present has the value null. It therefore contains an int, set to zero, and a bool, set to false. Now on another thread you write the nullable int "5" to x. It is perfectly legal for another thread to read the non-nullable int zero from x, because the "true" in the bool could be set before the 5 is set to the int.
不,因为
int?
实际上是一个由int
和bool
组成的结构体 (Nullable
) >。No, since an
int?
is actually a struct (Nullable<int>
) composed of anint
and abool
.来自 http://msdn.microsoft.com/en-us/library/b3h38hb0 .aspx:
From http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx: