gpt4 book ai didi

c - 普通 int 上的 stdatomic.h 函数 - 产生未定义或实现定义的行为?

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:46 25 4
gpt4 key购买 nike

在 GCC 中,这样的东西可以编译并且可能像预期的那样工作:

#include <stdatomic.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
(void)argc;

int x = 23;
// XXX
// instead of:
// _Atomic int x = 23;

int exp = atoi(argv[1]);
int y = atoi(argv[2]);

printf("x = %d, exp = %d, y = %d\n", x, exp, y);

bool b = atomic_compare_exchange_strong(&x, &exp, y);

printf("x = %d, exp = %d, y = %d => %s\n", x, exp, y, b ? "true" : "false");
return 0;
}

C reference says about such atomic functions :

This is a generic function defined for all atomic object types A. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and volatile (e.g. memory-mapped I/O) atomic variables. C is the non-atomic type corresponding to A.

这意味着像 atomic_compare_exchange_strong() 这样的原子函数不是为非原子类型定义的。

既然 int 是非原子类型,上面的代码是否会产生未定义的行为?

或者 C 标准是否将此指定为实现定义的行为?

(实现也能够将 int 定义为原子类型 - 因此基本上等同于 _Atomic int)

最佳答案

不对原子函数使用 _Atomic 类型绝对是未定义的行为。我很惊讶编译器没有提示,但 C 非常宽容。当多个线程同时修改同一内存位置时,原子函数为它们的行为提供了非常具体的保证。您的简单示例实际上并未证明这一点。

阅读 atomic types 的描述:

Objects of atomic types are the only objects that are free from data races, that is, they may be modified by two threads concurrently or modified by one and read by another.

通过不使用原子类型,您不再保证能够以原子方式访问值,从而使原子函数无用。

关于c - 普通 int 上的 stdatomic.h 函数 - 产生未定义或实现定义的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58471341/

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