Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is assignment equivalent to load/store for std::atomic<bool>

I see that this is potentially answered in question Must I call atomic load/store explicitly?.

So for sake of clarity I will restate my question succinctly in the hopes that future readers find this clear.

Is

std::atomic<bool> b(false);
bool x = b;

Same as

std::atomic<bool> b(false);
bool x = b.load();

And

std::atomic<bool> b(false);
b = true;

Same as

std::atomic<bool> b(false);
b.store(true);

If this is indeed the case then:

  1. why have 2 options? what is the apparent benefit?
  2. Is it good practice when dealing with atomics to prefer the more verbose load()/store() over the potentially confusing assignment(=) which could mean either depending on whether LHS or RHS is the atomic.

NOTE I am already aware of the fact that both variables cannot be std::atomic i.e LHS and RHS as it is not possible to read and write atomically in one instruction.

like image 355
BGR Avatar asked Jan 21 '16 05:01

BGR


People also ask

Is assignment atomic in C++?

no, its not..... you need to use a locking primitive of some sort.

What is an Atomic load?

atomic::loadAtomically loads and returns the current value of the atomic variable. Memory is affected according to the value of order .

Is Atomic bool necessary?

You need atomic<bool> to avoid race-conditions. A race-condition occurs if two threads access the same memory location, and at least one of them is a write operation. If your program contains race-conditions, the behavior is undefined.


1 Answers

Yes, they are the same. I think the reason the overloaded operators are provided is for convenience. Not to mention making it easier to convert existing code to use atomics.

Personally, I prefer to be explicit with load and store always. I think it's better practice and forces you to remember that you're dealing with an atomic.

Also, those functions allow you to specify other memory orders, which is not possible with the overloaded operator versions.

like image 90
paddy Avatar answered Sep 23 '22 17:09

paddy