C 中非原子类型的原子操作是原子的吗?

发布于 2025-01-17 02:23:48 字数 369 浏览 1 评论 0原文

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);
}

我的问题:上面对非原子对象xatomic_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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凉世弥音 2025-01-24 02:23:48

标准中定义了类型 A 的原子对象

但是我们可以打电话

GCC 来接受它。但在 clang 上你会得到一个错误。

上面对非原子对象x的atomic_fetch_add操作是否保证是原子的?

不。在标准中,您提供的代码的行为没有定义,没有任何形式的保证。来自 https://port70.net/~nsz/c/c11/n1570 .html#7.17

5 在以下概要中:

  • A 指的是一种原子类型。 [...]

然后所有函数都按照 A 定义,如 https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2

Catomic_fetch_key(易失性A*对象,M操作数);

原子类型是带有_Atomic的类型。

on an atomic object of type A is defined in the standard

But we can call

GCC will accept it. But on clang you'll get an error.

is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?

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 :

5 In the following synopses:

  • An A refers to one of the atomic types. [...]

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文