C17 标准指定了一系列原子操作。例如,对 A
类型的原子对象的原子读写修改操作在标准中定义为:
C atomic_fetch_add(volatile A *object, M operand);
但是我们可以在非原子类型上调用atomic_fetch_add
:
static int x;
static int foo(void *arg) {
atomic_fetch_add(&x, 3);
}
我的问题:上述atomic_fetch_add
对非原子对象x
的操作是否保证是原子的?
最佳答案
on an atomic object of type A is defined in the standard
But we can call
GCC 会接受它。但是在 clang 上你会得到一个错误。
is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?
没有。在标准中,您提供的代码的行为没有定义,没有任何形式的保证。来自 https://port70.net/~nsz/c/c11/n1570.html#7.17 :
5 In the following synopses:
- An A refers to one of the atomic types. [...]
然后所有函数都根据 A
定义,如 https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 :
C atomic_fetch_<i>key</i>(volatile A *object, M operand);
Atomic type是 _Atomic
的类型.
关于c - C中非原子类型的原子操作是原子的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71606318/