Search code examples
c++reinterpret-castmemory-layoutstdatomic

writing to std::atomic after converting to char*


Sorry if my doubt is too naive. But I have a difficulty in typecasting std::atomic to char* type. Is casting from std::atomic to char is valid?

Can I write to such type casted variable. I am sure that there will be no multithreaded reads/writes while a thread tries to write into the variable.(I understand that, there is no need for using atomics when there will be no concurrent access on this variable)

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

Is it safe to do?

EDIT: I am not sure if its worth mentioning. In my code,

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

The above is how the std::atomic< uint8_t> is created (as char and type casted to std::atomic type).

Thanks :)


Solution

  • I don't think it's safe at all. The C++ Standard does not guarantee std::atomic<uint8_t> to be lock-free. If it is not, then there might be, e.g., a mutex member variable stored in every std::atomic<uint8_t> object starting at its first byte. In such a case, your command *data |= mask; would manipulate a bit of this mutex, which might completely break its internal implementation.


    This might be also a relevant question: Is it possible to get the address of the underlying storage for an atomic_int?.