C 中非原子类型的原子操作是原子的吗?
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);
}
我的问题:上面对非原子对象x
的atomic_fetch_add
操作是否保证是原子的?
The C17 standard specifies a list of atomic operations. For example, an atomic read-write-modify operation on an atomic object of type A
is defined in the standard as:
C atomic_fetch_add(volatile A *object, M operand);
But we can call atomic_fetch_add
on non-atomic types:
static int x;
static int foo(void *arg) {
atomic_fetch_add(&x, 3);
}
My question: is the above atomic_fetch_add
operation on the non-atomic object x
guaranteed to be atomic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
GCC 来接受它。但在 clang 上你会得到一个错误。
不。在标准中,您提供的代码的行为没有定义,没有任何形式的保证。来自 https://port70.net/~nsz/c/c11/n1570 .html#7.17:
然后所有函数都按照
A
定义,如 https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 :Catomic_fetch_key(易失性A*对象,M操作数);
原子类型是带有
_Atomic
的类型。GCC will accept it. But on clang you'll get an error.
No. In the standard the behavior of the code you presented is not defined, there is no guarantee of any kind. From https://port70.net/~nsz/c/c11/n1570.html#7.17 :
And then all the functions are defined in terms of
A
, like in https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 :C atomic_fetch_key(volatile A *object, M operand);
Atomic type is a type with
_Atomic
.