为int?线程安全的? [英] Is int? thread safe?

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

问题描述

我知道,在.net所有32位类型(例如, 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).

不过,也同样适用于诠释?(可空INT)?

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

推荐答案

现在的问题是措辞不当,因而在回答混乱为止。这个问题应该是是读取和写入到一个int类型的变量?保证是的原子的?

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:

读取及以下数据类型的读写是原子:布尔,字符,字节,为sbyte,总之,USHORT,UINT,整型,浮点和引用类型。此外,当枚举类型的具有基础类型在previous读写也是原子的。读取和其他类型,包括长,ULONG,双,和小数,以及用户自定义类型的读写,不能保证是原子的。

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,它在present的值为空。因此,它包含了一个int,设置为零,和一个布尔值,设置为false。现在,在另一个线程你写的可空INT5为x。这是完全合法的另一个线程读取非可空INT零从x,因为在布尔真之前的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.

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

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