c# 中的原始数据类型是原子的(线程安全的)吗? [英] Are primitive data types in c# atomic (thread safe)?
问题描述
例如,多线程时是否需要锁定bool
值?
For example, do I need to lock a bool
value when multithreading?
推荐答案
没有原子类型这样的东西.只有操作可以是原子的.
There is no such thing as an atomic type. Only operations can be atomic.
读取和写入适合单个字的数据类型(在 32 位处理器上为 int
,在 64 位处理器上为 long
)在技术上是原子的"",但抖动和/或处理器可以决定对指令重新排序,从而产生意外的竞争条件,因此您需要使用 lock
序列化访问,使用 Interlocked
类写入(在某些情况下读取),或声明变量 volatile
.
Reading and writing a data type that fits into a single word (int
on a 32-bit processor, long
on a 64-bit processor) is technically "atomic", but the jitter and/or processor can decide to reorder instructions and thus create unexpected race conditions, so you either need to serialize access with lock
, use the Interlocked
class for writes (and in some cases reads), or declare the variable volatile
.
简短的回答是:如果两个不同的线程可能访问同一个字段/变量,并且其中至少有一个正在写入,则需要使用某种锁定.对于通常是 Interlocked
类的基本类型.
The short answer is: If two different threads may access the same field/variable and at least one of them will be writing, you need to use some sort of locking. For primitive types that's generally the Interlocked
class.
这篇关于c# 中的原始数据类型是原子的(线程安全的)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!