gpt4 book ai didi

c# - C#中的基本算术运算是原子的吗

转载 作者:太空狗 更新时间:2023-10-30 00:15:54 25 4
gpt4 key购买 nike

基本算术运算线程安全吗?

比如对一个全局变量有++操作,会被不同的线程修改,是否需要加锁?

例如

void MyThread() // can have many running instances
{
aGlobal++;
}

或者应该是

void MyThread()
{
lock( lockerObj)
{
aGlobal++;
}
}

最佳答案

The spec总结得很好。第 5.5 节,“变量引用的原子性”:

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. Aside from the library functions designed for that purpose, there is no guarantee of atomic read-modify-write, such as in the case of increment or decrement.

结论:

  • 独立读/写是原子的(但只针对某些数据类型)
  • 读取/修改/写入(例如i++)从不是原子的
  • 您可以使用 Interlocked在尚未保证时实现原子性的类方法

Interlocked 功能不够用的情况下,除了使用同步原语之外别无选择,例如 Monitor.Enter (编译器还通过 lock 语句公开)。

关于c# - C#中的基本算术运算是原子的吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10530337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com