Is int? thread safe?(是整数吗?线程安全吗?)
问题描述
我知道在 .Net 中所有 32 位类型(例如,int
、bool
等)都是线程安全的.也就是说,不会有部分写入(根据规范).
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.
这篇关于是整数吗?线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是整数吗?线程安全吗?
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30