MRB
MRB

Reputation: 3812

Non atomic operation on atomic variables

Suppose I have this code:

std::atomic<int> a1;
std::atomic<int> a2;
std::atomic<int> a3;

std::atomic_store(&a1, 1);
std::atomic_store(&a2, 1);
std::atomic_store(&a3, 2);

int a2Value = std::atomic_load_explicit(&a2, std::memory_order_relaxed);
int a3Value = std::atomic_load_explicit(&a3, std::memory_order_relaxed);

std::atomic_compare_exchange_strong_explicit(
    &a1, 
    &a2Value, 
    a3Value, 
    std::memory_order_relaxed, 
    std::memory_order_relaxed);

Can I replace that with the following to avoid two atomic reads (is it safe?):

a2Value = static_cast<int>(a2);
a3Value = static_cast<int>(a3);

std::atomic_compare_exchange_strong_explicit(
    &a1, 
    &a2Value, 
    a3Value, 
    std::memory_order_relaxed, 
    std::memory_order_relaxed);

Also can I use something like this code to write an atomic variable without it being an atomic write?

*reinterpret_cast<int*>(&a2) = 5;

Upvotes: 3

Views: 1791

Answers (2)

curiousguy
curiousguy

Reputation: 8268

It would be great to be able to use atomic and non atomic types interchangeably when atomicity is or isn't needed. However nothing in the C++ model allow it and lots of things go against it.

But the memory model is unsound in the first place (as in: it doesn't define the behavior of anything, it's senseless) so it should be rebuild from scratch and then what you propose should be considered.

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182761

Nope, you can't.

If you have a platform where reads of aligned integers are always atomic, then you haven't avoided any atomic operations. If you have a platform where reads of aligned integers aren't always atomic, then the code is obviously unsafe.

Upvotes: 1

Related Questions