将 atomic<T> 转换为 T 是否安全

Is it safe to cast atomic<T> to T

我有两个问题:

  1. 在一般情况下,使用原子作为 T 并在它们之间互换切换是否安全?
  2. 在 futex 的情况下进行转换安全吗?

我知道对非原子类型执行原子操作是未定义的行为,但我找不到相反的答案。例如,它按预期编译和执行:

std::atomic_int foo = 5;
int* bar = reinterpret_cast<int*>(&foo);
(*bar)++;
std::cout << (*bar) << std::endl;

关于第二个问题,Linux联机帮助页在FUTEX_WAIT操作中说

The load of the value of the futex word is an atomic memory access (i.e., using atomic machine instructions of the respective architecture). This load, the comparison with the expected value, and starting to sleep are performed atomically and totally ordered with respect to other futex operations on the same futex word.

那么下面的代码安全吗?

std::atomic_int32_t val = 0;
syscall(SYS_futex, reinterpret_cast<int*>(&val), FUTEX_WAIT_PRIVATE, 0, nullptr);

In the general case is it safe to use an atomic as a T and switch between them interchangeably?

reinterpret_cast 无关。 reinterpret_cast 只有在明确列出的情况下才是安全的,而这不是一个。

但是,您可以使用 std::atomic_ref.

T 临时转换为原子对象

In the case of a futex is it safe to do the cast?

没有

然而,std::atomic_refstd::atomic有相似的API,包括wait