转换为 char* 后写入 std::atomic

writing to std::atomic after converting to char*

对不起,如果我的怀疑太天真了。但是我很难将 std::atomic 类型转换为 char* 类型。从 std::atomic to char 转换是否有效?

我可以写入这种类型的转换变量吗?我确信当一个线程试图写入变量时不会有多线程reads/writes。(我明白,当这个变量没有并发访问时不需要使用原子)

std::atomic<uint8_t>* data_;
char *data = reinterpret_cast<char*>(data_);
*data |= mask;

这样做安全吗?

编辑: 我不确定它是否值得一提。在我的代码中,

char *raw;
// variable raw is allocated
std::atomic<uint8_t>* data_ = reinterpret_cast<std::atomic<uint8_t>*>(raw);

以上是 std::atomic< uint8_t> 的创建方式(将 char 和类型转换为 std::atomic 类型)。

谢谢:)

我认为它一点也不安全。 C++ 标准不保证 std::atomic<uint8_t>lock-free。如果不是,那么可能有一个 mutex 成员变量存储在每个 std::atomic<uint8_t> 对象中,从它的第一个字节开始。在这种情况下,您的命令 *data |= mask; 将操纵此互斥量的一部分,这可能会完全破坏其内部实现。


这可能也是一个相关问题:Is it possible to get the address of the underlying storage for an atomic_int?