在C#中的原始数据类型的原子(线程安全的)? [英] Are primitive data types in c# atomic (thread safe)?

查看:374
本文介绍了在C#中的原始数据类型的原子(线程安全的)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我需要多线程时锁定布尔价值?

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.

阅读和编写适合单个字( INT 在32位处理器,在64位处理器)在技术上是原子,但抖动和/或处理器可以决定重新排序指令,从而创造意想不到的竞争条件,让你无论是需要序列化与锁定,用于写入互锁类访问(在某些情况下读取),或声明变量挥发性

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.

简短的回答是:如果两个不同的线程可以访问相同的字段/变量,其中至少有一个会写,你需要使用某种形式的锁定。对于基本类型通常是在互锁类。

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屋!

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