是整数吗?线程安全吗? [英] Is int? thread safe?

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

问题描述

我知道在 .Net 中所有 32 位类型(例如,intbool 等)都是线程安全的.也就是说,不会有部分写入(根据规范).

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).

但是,同样适用于 int?(可为空的 int)吗?

But, does the same apply for int? (nullable int)?

推荐答案

这个问题措辞不佳,因此到目前为止的答案很混乱.问题应该是是否对 int 类型的变量进行读写?保证是 atomic?"

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:

以下数据类型的读写是原子的:bool、char、byte、sbyte、short、ushort、uint、int、float 和引用类型.此外,上一个列表中具有基础类型的枚举类型的读取和写入也是原子的.其他类型的读写,包括 long、ulong、double 和 decimal,以及用户定义的类型,不保证是原子的.

Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list are also atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, are not guaranteed to be atomic.

线程完全有可能从可为空类型的共享内存变量中读取部分写入的值.

It is entirely possible for a thread to read a partially written value from a shared-memory variable of nullable type.

例如,假设你有一个 int?变量 x 目前的值为 null.因此,它包含一个设置为零的 int 和一个设置为 false 的 bool.现在在另一个线程上,您将可为空的 int "5" 写入 x.另一个线程从 x 读取不可为空的 int 零是完全合法的,因为 bool 中的true"可以在 5 设置为 int 之前设置.

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.

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

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