user997112
user997112

Reputation: 30615

Compare and exchange weak an atomic variable

I have code (updated to correct the union-struct ordering):

union A {
    struct {
         short b;
         short c;
    };

    std::atomic<int> d;
}

and I want to swap both b and c (hence the atomic d) with the value zero, using compare_exchange_weak(). So I have this:

A a;
.
.
.
std::atomic<int32_t> x = a.d.load(std::memory_order_relaxed);
int32_t valToReplace = 0;

return a.d.compare_exchange_weak(valToReplace, x, std::memory_order_release, std::memory_order_relaxed);

How do I do this? The argument to compare_exchange_weak(), x, cannot be atomic- so I am confused?

Upvotes: 0

Views: 337

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254431

The local variable x shouldn't be atomic. There's no reason for it to be, and it can't be used as the argument to compare_exchange_weak, which expects a regular value.

I won't comment on whatever you're trying to do with the union, since that makes no sense to me.

Upvotes: 1

Related Questions