Are these multiple assignments of atomic variables, atomic operation?

consider that I have two atomic logic elements as follows.

private:
    std::atomic_bool x;
    std::atomic_bool y;

Can I say that the next operation is atomic? or do I need to use lock_guardto make sure they are assigned together?

x = y = true; // are two bools assigned together atomically?

also consider in another thread, I want to read these logical lines.

if(!x && !y) ...

My assumption is that it is not atomic, maybe it is better to use atomic<int>instead?

+4
source share
2 answers

, . , , , . , y , - ( , - , operator= ), x. .

, , , . ; char , 16- , (IMHO) : .

struct MyBools {
  bool x;
  bool y;
};

bool operator==(const MyBools& lhs, const MyBools& rhs) {
    return lhs.x == rhs.x && lhs.y == rhs.y;
}

using MyAtomicBools = std::atomic<MyBools>;

MyAtomicBools b{true, true};
...
if (b == MyBools{false, false}) { ... }

, 16- . gcc, , ; + , clang : https://godbolt.org/g/moiT9Y.

+4
x = y = true; // are two bools assigned together atomically?

, x y : , .

, ¹, , x y .

- , , .

if(!x && !y) ...

: CPU , , , ²; .

¹ , , , , , ² , , CPU
³ , / : 1Mo , .

+2

Source: https://habr.com/ru/post/1682564/


All Articles